【问题标题】:Passing a column name as a variable to a select statement in a function in python / pandas将列名作为变量传递给python / pandas函数中的select语句
【发布时间】:2023-03-25 12:54:01
【问题描述】:

假设我有一个函数:

def retrieve (c,y):
     df = pd.read_sql("select Year, ? from table where Year=? ",db, params=(c,y))
     return df

我希望能够调用如下函数:

retrieve("col_name",2001)

当我将列名作为可以传递的变量删除时,它可以正常工作。但我也需要能够传递列名。有什么方法可以让我完成这项工作吗?

【问题讨论】:

  • 将列名作为变量传递时遇到什么问题?

标签: python python-2.7 pandas sqlite dataframe


【解决方案1】:

您可以尝试在 Python 中格式化查询字符串,而不是使用准备好的语句。

querysting = "select Year, {} from table where Year={}".format(c,y)
df = pd.read_sql(querystring,db)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2023-02-01
    • 1970-01-01
    • 2017-08-15
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多