pandas 的 read_sql 带有 WHERE 条件的值列表 [英] pandas' read_sql with a list of values for WHERE condition
问题描述
假设一个数据帧scoreDF
:
date time score
sec_code
1048 2015-02-25 09:21:00 28
2888 2015-02-25 09:21:00 25
945 2015-02-25 09:21:00 23
4 2015-02-25 09:21:00 22
669 2015-02-25 09:21:00 15
我需要进行 MySQL 查询以检索与 scoreDF.index
中的值匹配的所有行,即 sec_code
列.
I need to make a MySQL query to retrieve all rows matching the values in scoreDF.index
i.e. sec_code
column.
通常我会去循环:
finalResultDF = DataFrame()
queryString = 'SELECT * FROM tableA WHERE sec_code = ' + code
for code in scoreDF.index:
queryResultDF = sql.read_sql(queryString, con)
finalResultDF.append(queryResultDF)
是否可以在没有循环传递值列表的情况下以不同的方式执行此操作,即 scoreDF.index
作为 WHERE 条件?我在谷歌上搜索了几个小时,有些人提到了 read_sql
的参数",但我无法弄清楚.
Would it be possible to do this differently without a loop passing a list of values i.e. scoreDF.index
as WHERE condition? I Googled for hours and some mentions 'parameter' to read_sql
but I couldn't figure it out.
推荐答案
你实际上可以在没有任何循环的情况下做到这一点.
You can actually do this without any loop.
queryString = 'SELECT * FROM tableA WHERE sec_code in '+tuple(scoreDF.index)
这将直接给出结果.这是假设 scoreDF.index
是一个 list
.如果它已经是一个 tuple
那么没有类型转换是必需的.
This will give the results directly.This is assuming scoreDF.index
is a list
.If it is already a tuple
then no typecasting is required.
这篇关于pandas 的 read_sql 带有 WHERE 条件的值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!