0

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 Answer 1

2

To create your query you could do something like this :

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')"
Sign up to request clarification or add additional context in comments.

3 Comments

Here it put all the column names in the "IN" clause of the query. But what I am looking for is something like this. print df['users'] >>> abc >>> def >>> ghi >>> jkl and my query should look like "select * from users where id in ('abc','def','ghi','jkl')"
would you be able to help me with this please.
@Aravindh I edited the anwser. Is that what you wanted ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.