Reputation: 1587
I have a pandas dataframe as follows...
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['abc', 11], ['xyz', 21],['pqr',31]]),columns=['member','value'])
What I need is to collapse the column 'member' inside a single string with the output as an SQL query as follows...
"select * from table1 where member in ('abc','xyz','pqr')"
In my original data I have a large number of values. I couldn't figure out a way to collapse it from previous question search. Is there a way to do this without using a loop? Thanks.
Upvotes: 0
Views: 3282
Reputation: 31682
You can use tolist method of interesting column then convert it to tuple and then to string:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['abc', 11], ['xyz', 21],['pqr',31]]),columns=['member','value'])
sql_string = "select * from table1 where member in "
members = tuple(df.member.tolist())
query = sql_string + str(members)
Upvotes: 3