【问题标题】:Use pandas series as input parameter使用 pandas 系列作为输入参数
【发布时间】:2021-11-21 17:09:11
【问题描述】:

我是一名尝试学习 Python 的 R 用户。在 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”我想使用参数。

【问题讨论】:

标签: python r pandas arguments parameter-passing


【解决方案1】:

OP 正在寻找类似的东西

query = f"select * from table where ID in ({','.join(df['ID'].astype(str))})"

更多从list创建这个查询的方法,也可以在评论中查看@Erfan提供的this post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2019-11-30
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多