【问题标题】:Replace a string in dataframe's column with values from other columns Pandas用其他列 Pandas 中的值替换数据框列中的字符串
【发布时间】: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


    【解决方案1】:

    我认为你的答案很接近。在 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)
    

    【讨论】:

    • 天哪,真是一种解脱。是的,它的工作原理。在这上面花了一整天。非常感谢。
    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2014-02-06
    • 2017-01-27
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多