Steven
Steven

Reputation: 15273

using pandas df with map

I want to map my DF values into a string:

SQL = """select * from mytable where col1={0} and col2={1}"""

I tried this ListResult = map(lambda x :SQL.format(*x),DF[['Col1','Col2']])

but the output be like

[u'select * from mytable where col1 = C and col2=o', 
 u'select * from mytable where col1 = C and col2=o']

How can I generate a list of string completed with the values from my DF (the number of columns may vary according to the SQL)?


EDIT: add sample and expected result

> DF =  

 - Col1 Col2
 - 0     1591354166       12387796
 - 1     1596855166        8833942
 - 2     1626196066       12584655

expected result:

[select * from mytable where col1=1591354166 and col2=12387796,
 select * from mytable where col1=1596855166 and col2=8833942, 
 select * from mytable where col1=1626196066 and col2=12584655]

Upvotes: 2

Views: 87

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210902

is that what you want?

In [50]: ListResult = df.apply(lambda x: SQL.format(x.Col1, x.Col2), axis=1).tolist()

In [51]: ListResult
Out[51]:
['select * from mytable where col1=1591354166 and col2=12387796',
 'select * from mytable where col1=1596855166 and col2=8833942',
 'select * from mytable where col1=1626196066 and col2=12584655']

Upvotes: 0

jezrael
jezrael

Reputation: 863226

I think you can add values for generating numpy array from DataFrame:

SQL = """select * from mytable where col1='{0}' and col2='{1}'"""

print map(lambda x :SQL.format(*x),df[['Col1','Col2']].values)

["select * from mytable where col1='1591354166' and col2='12387796'",
 "select * from mytable where col1='1596855166' and col2='8833942'", 
 "select * from mytable where col1='1626196066' and col2='12584655'"]

Upvotes: 1

Related Questions