【发布时间】:2021-01-22 19:10:24
【问题描述】:
在熊猫方面需要一些帮助。 我有一个查询 stmnt-
query = "update table1 set Draft = firstvalue ,lastupdated=now() where StatsMonth = secondvalue and Code =thirdvalue"
我有一个包含以下列的 df
df['payments'], df['pub'] , df['query'] 和一个名为 t2 ='2020-12-24'的变量
pub payments query
123 59495.17 update table1 set Draft ...
786 887.50 update table1 set Draft ...
456 4.58 update table1 set Draft ...
789 0.00 update table1 set Draft ...
221 0.00 update table1 set Draft ...
目标是使用来自 df['payments'] , t2 的值更新查询列中的字符串 - firstvalue、secondvalue、thirdvalue。 df[‘pub’]
最终结果应该是这样的。
123 59495.17 update table1 set Draft =59495.17, lastupdated=now() where StatsMonth = '2020-12-24' and Code =123
786 887.50 update table1 set Draft =887.50 , lastupdated=now() where StatsMonth = '2020-12-24' and Code =786
所以我们使用其他两列的值并将其替换为查询中的那些字符串。
这是我正在应用的转换列表 -
df['query']=df.apply(lambda x: x['query'].replace('firstvalue', str(df['payments'])), axis=1)
df['query']=df.apply(lambda x: x['query'].replace('secondvalue', t2), axis=1)
df['query']=df.apply(lambda x: x['query'].replace('thirdvalue', str(df['pub'])), axis=1)
但结果对于每一行都有相同的值
这就是它的外观 -
pub payments query
123 59495.17 update table1 set Draft = 0 59495.17
786 887.50 update table1 set Draft = 0 59495.17
它截断查询的其余部分,并在查询前添加一个零。
所有行都重复相同的值。
知道我在这里做错了什么吗?
【问题讨论】:
标签: python pandas lambda apply