【发布时间】: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