Python 替换数据帧中的字符串';s列与其他列中的值相同

Python 替换数据帧中的字符串';s列与其他列中的值相同,python,pandas,lambda,apply,Python,Pandas,Lambda,Apply,我需要一些关于熊猫的帮助。 我有一个疑问- query=“update table1 set Draft=firstvalue,LastUpdate=now(),其中StatsMonth=secondvalue,code=thirdvalue” 我有一个带有以下列的df df['payments']、df['pub']、df['query']和一个名为t2='2020-12-24'的变量 pub payments query 123 59495.17 updat

我需要一些关于熊猫的帮助。 我有一个疑问-

query=“update table1 set Draft=firstvalue,LastUpdate=now(),其中StatsMonth=secondvalue,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 
它将截断查询的其余部分,并在查询前加上一个零

同时,所有行都重复相同的值


你知道我做错了什么吗?

我想你的答案很接近。在lambda中,不要调用
df
尝试
x

df['query']=df.apply(lambda x:x['query'].replace('firstvalue',str(x['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(x['pub'])),axis=1)

编辑1 由于t2替换没有引用数据框中的列,因此可以使用Series
str
方法

df['query']=df['query'].str.replace('secondvalue',t2)

哦,天哪,真是松了一口气。是的,它起作用了。花了整整一天的时间。非常感谢你。