【问题标题】:Replace part of a string with a pandas column as pattern将部分字符串替换为 pandas 列作为模式
【发布时间】:2021-09-24 04:01:09
【问题描述】:

我想在 pandas 列上使用 .str.replace() 方法,但将另一个 pandas 列作为模式

例如,

df = pd.DataFrame({'str1': ['abc','abcd','def'], 'str2': ['b','ab', 'ef']})

我想通过将str1 中的str2 字符串替换为空字符串来构建一个新列str1_replaced

这是我想要得到的结果:

   str1 str2 str1_replaced
0   abc    b            ac
1  abcd   ab            cd
2   def   ef             d

我已经尝试过:

df['str1_replaced'] = df['str1'].str.replace(df['str2'],"")

但我收到以下错误

TypeError: 'Series' 对象是可变的,因此它们不能被散列

有什么方法可以在不使用 for 循环的情况下实现这一点?我正在考虑使用 lambda 函数,但不知道具体怎么做。

【问题讨论】:

    标签: python pandas str-replace


    【解决方案1】:

    试试apply:

    df['str1_replaced'] = df.apply(lambda x: x['str1'].replace(x['str2'], ''), axis=1)
    

    >>> df
       str1 str2 str1_replaced
    0   abc    b            ac
    1  abcd   ab            cd
    2   def   ef             d
    >>> 
    

    或尝试列表理解:

    df['str1_replaced'] =[x.replace(y, '') for x, y in zip(df['str1'], df['str2'])]
    

    【讨论】:

    • @fmarm 太好了!还添加了另一个解决方案:)
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 2020-09-08
    • 2021-06-20
    • 2014-03-22
    相关资源
    最近更新 更多