使用 pandas 系列作为输入参数
Use pandas series as input parameter
我是 R 用户,正在尝试使用 Python。在 R 中,我经常使用向量作为参数传递给 SQL 查询。例如,
ID <- c(1,2,3,4,5)
df <- dbGetQuery(con, paste("select * from table where ID in (", ID, ")")
如何在 Python 中实现此目的?我有一个数据框,想将其中一列用作参数。因此,使用这样的数据框,
data = {'ID': [1,2,3,4,5],
'Value': [10,20,30,40,50]}
df = pd.DataFrame(data)
[编辑]
所以基本上我需要一个字符串来读取“Select * from table where ID in (1,2,3,4,5)”除了,而不是手动输入“1,2,3, 4,5" 我要用参数
OP 正在寻找类似
的东西
query = f"select * from table where ID in ({','.join(df['ID'].astype(str))})"
有关从 list
创建此查询的更多方法,还可以查看@Erfan 在评论中提供的 this post。
我是 R 用户,正在尝试使用 Python。在 R 中,我经常使用向量作为参数传递给 SQL 查询。例如,
ID <- c(1,2,3,4,5)
df <- dbGetQuery(con, paste("select * from table where ID in (", ID, ")")
如何在 Python 中实现此目的?我有一个数据框,想将其中一列用作参数。因此,使用这样的数据框,
data = {'ID': [1,2,3,4,5],
'Value': [10,20,30,40,50]}
df = pd.DataFrame(data)
[编辑] 所以基本上我需要一个字符串来读取“Select * from table where ID in (1,2,3,4,5)”除了,而不是手动输入“1,2,3, 4,5" 我要用参数
OP 正在寻找类似
的东西query = f"select * from table where ID in ({','.join(df['ID'].astype(str))})"
有关从 list
创建此查询的更多方法,还可以查看@Erfan 在评论中提供的 this post。