簡體   English   中英

將數據框列中的字符串替換為其他列 Pandas 中的值

[英]Replace a string in dataframe's column with values from other columns Pandas

在 pandas 方面需要一些幫助。 我有一個查詢 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['酒吧']

最終結果應該是這樣的。

  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 

它截斷查詢的 rest 並在查詢前添加一個零。

此外,所有行都重復相同的值。

知道我在這里做錯了什么嗎?

我認為你的答案很接近。 在 lambda 而不是調用df try 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM