Pandas Dataframe - Mysql从<a column="" from="" dataframe="">

时间:2016-07-13 06:31:28

标签: mysql pandas dataframe

I have a dataframe column which is a set of user ids. I would like to run a query on mysql based on this column values like :

"SELECT * FROM users WHERE user_id IN ( 'COLUMN IN DATAFRAME' ) 

How could I do this.

1 个答案:

答案 0 :(得分:2)

要创建查询,您可以执行以下操作:

import pandas as pd
df = pd.DataFrame(['abc', 'bce'], columns=['users'])
df
>>>   users
>>> 0   abc
>>> 1   bce

query = "SELECT * FROM users WHERE user_id in (%s)" % ','.join(df['users'])
>>> 'SELECT * FROM users WHERE user_id in (abc,bce)'
query = "SELECT * FROM users WHERE user_id in ('%s')" % "','".join(df['users'])
>>> "SELECT * FROM users WHERE user_id in ('abc','bce')"