使用pandas df和map

时间:2016-04-20 07:43:13

标签: python-2.7 pandas

我想将DF值映射到字符串中:

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

我试过这个ListResult = map(lambda x :SQL.format(*x),DF[['Col1','Col2']])

但输出如

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

如何使用DF中的值生成完成的字符串列表(列数可能因SQL而异)?

编辑:添加样本和预期结果

> DF =  

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

预期结果:

[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]

2 个答案:

答案 0 :(得分:1)

我认为您可以添加values以从numpy array生成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'"]

答案 1 :(得分:0)

是你想要的吗?

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']