如何使用 pandas 替换所有列中的所有字符串? [英] How to replace all string in all columns using pandas?

查看:77
本文介绍了如何使用 pandas 替换所有列中的所有字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熊猫中,如何用<&'代替&amp;&amp可能在字符串中的任何位置的所有列中显示?

In pandas, how do I replace &amp; with '&' from all columns where &amp could be in any position in a string?

例如,在标题"列中,如果有一个值"Good &amp; bad",则如何将其替换为"Good&不好"?

For example, in column Title if there is a value 'Good &amp; bad', how do I replace it with 'Good & bad'?

推荐答案

使用 replace regex=True用于替换子字符串:

Use replace with regex=True for substrings replacement:

df = pd.DataFrame({'A': ['Good &amp; bad', 'BB', 'CC', 'DD', 'Good &amp; bad'],
                   'B': range(5),
                   'C': ['Good &amp; bad'] * 5})

print (df)
                A  B               C
0  Good &amp; bad  0  Good &amp; bad
1              BB  1  Good &amp; bad
2              CC  2  Good &amp; bad
3              DD  3  Good &amp; bad
4  Good &amp; bad  4  Good &amp; bad

df = df.replace('&amp;','&', regex=True)
print (df)
            A  B           C
0  Good & bad  0  Good & bad
1          BB  1  Good & bad
2          CC  2  Good & bad
3          DD  3  Good & bad
4  Good & bad  4  Good & bad

如果只想替换一列:

df['A'] = df['A'].replace('&amp;','&', regex=True)
print (df)
            A  B               C
0  Good & bad  0  Good &amp; bad
1          BB  1  Good &amp; bad
2          CC  2  Good &amp; bad
3          DD  3  Good &amp; bad
4  Good & bad  4  Good &amp; bad

这篇关于如何使用 pandas 替换所有列中的所有字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆