SQL Pandas DataFrame中的where in子句使用列 [英] SQL where in clause using column in pandas dataframe
本文介绍了SQL Pandas DataFrame中的where in子句使用列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有ID列的pandas数据框.我需要运行另一个sql查询,该查询的'WHERE'子句由上述列中的所有ID决定.
I have a pandas dataframe that has a column of IDs. I need to run another sql query whose 'WHERE' clause is dictated by all of the IDs in the aforementioned column.
例如:
df1 = DataFrame({'IDs' : [1,2,3,4,5,6]})
query = """ Select id, SUM(revenue) AS revenue WHERE id IN (***want df1['IDs'] here***) Group by 1"""
df2 = my_database.select_dataframe(query)
推荐答案
将系列转换为字符串
str = ','.join([str(x) for x in df1['IDs'].tolist()])
str
'1,2,3,4,5,6'
然后,将其插入查询字符串-
And, then insert it into the query string -
qry = "Select id, SUM(revenue) AS revenue WHERE id IN (%s) Group by 1" % str
qry
'Select id, SUM(revenue) AS revenue WHERE id IN (1,2,3,4,5,6) Group by 1'
这篇关于SQL Pandas DataFrame中的where in子句使用列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文