gpt4 book ai didi

python - 用 pandas 将字符串替换为另一列中的相应字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:08:30 24 4
gpt4 key购买 nike

我有一个名为 df 的数据框,看起来像这样:

pd.DataFrame({
'column1' : ['client#1 is #name#', 'client#2 is #name#'],
'column2': ['josh', 'max']}
)

column1 column2
0 client#1 is #name# josh
1 client#2 is #name# max

我正在尝试用 column2 的值替换 column1 中的短语“#name”。我希望最终结果如下所示:

enter image description here

我试过如下几种方法:

df['column1'] = df['column1'].replace(["#name#"], df['column2'])

但我不确定如何获取第 1 列中的特定短语“#name#”并将其替换为第 2 列的值。非常感谢任何有关如何处理此问题的建议!

最佳答案

如果是字符串,并且没有 NaN,我建议在列表理解中调用 str.replace 以提高速度:

df['column1'] = [
x.replace('#name#', y) for x, y in zip(df.column1, df.column2)]

df
column1 column2
0 client#1 is josh josh
1 client#2 is max max

为什么列表理解对于字符串操作值得?您可以在 For loops with pandas - When should I care? 阅读更多内容.


您可以考虑的另一个有趣的选择是将 str.replace 替换为 iter:

it = iter(df.column2)
df['column1'] = df.column1.str.replace('#name#', lambda x: next(it))

df
column1 column2
0 client#1 is josh josh
1 client#2 is max max

应该可以很好地处理 NaN 和混合数据类型(但会更慢)。


@Vaishali 的一个更简单的 replace 选项,如果“#name#”子字符串总是在字符串的末尾,它将起作用。

df['column1'] = df.column1.add(df.column2).str.replace('#name#', '')
df
column1 column2
0 client#1 is josh josh
1 client#2 is max max

关于python - 用 pandas 将字符串替换为另一列中的相应字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com