gpt4 book ai didi

python - pandasql::sqldf 不捕获循环变量

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:38 25 4
gpt4 key购买 nike

我试图用 pandasql::sqldf 循环列表,但这个 sqldf 似乎没有捕获循环变量。以下是我的问题的程式化概述:

import pandas as pd
from pandasql import sqldf
from datetime import datetime

FreqGamePlay = pd.DataFrame({'CONTACT_WID' : [1, 2, 3, 1, 4],
'TITLE_NOMIN_DT' : pd.to_datetime(['20130102', '20140103', '20120518',
'20140317', '20111123']),
'FreqGamePlay' : [12, 9, 22, 4, 5]})
FreqGamePlay = FreqGamePlay[['CONTACT_WID', 'TITLE_NOMIN_DT', 'FreqGamePlay']]

periodsList = ['2012-12-26', '2012-02-28']
for i in periodsList:
temp = sqldf("select CONTACT_WID, sum(FreqGamePlay) as FGP from FreqGamePlay where TITLE_NOMIN_DT > i group by CONTACT_WID;", globals())
print(temp)

上述程序出现以下错误:

PandaSQLException: (sqlite3.OperationalError) no such column: i [SQL: 'select CONTACT_WID, sum(FreqGamePlay) as FGP from FreqGamePlay where TITLE_NOMIN_DT > i group by CONTACT_WID;']

但是如果我手动硬编码日期,它就可以正常工作:

for i in periodsList:
temp = sqldf("select CONTACT_WID, sum(FreqGamePlay) as FGP from FreqGamePlay where TITLE_NOMIN_DT > '2012-12-26' group by CONTACT_WID;", globals())
print(temp)

但是上面的效率不高,因为实际的程序有一个更大的日期列表。任何建议表示赞赏,谢谢

最佳答案

这是因为您直接在 SQL 字符串中包含了“i”变量,因此 Python 假定它是字符串的一部分,并且不会对变量进行求值(您可以注意到,在错误消息中,i 变量没有被它的值替换)值(value))。我建议您阅读一些有关使用 Python 字符串和变量的内容。在那之前,请尝试以下操作:

for i in periodsList:
query = "select CONTACT_WID, sum(FreqGamePlay) as FGP from FreqGamePlay where TITLE_NOMIN_DT > '{}' group by CONTACT_WID;".format(i)
temp = sqldf(query, globals())

大括号用作变量的占位符,format() 方法用于将占位符替换为变量值。

关于python - pandasql::sqldf 不捕获循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com