如何使用 pandas 替换所有列中的所有字符串? [英] How to replace all string in all columns using pandas?
本文介绍了如何使用 pandas 替换所有列中的所有字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在熊猫中,如何用<&'代替&
从&
可能在字符串中的任何位置的所有列中显示?
In pandas, how do I replace &
with '&' from all columns where &
could be in any position in a string?
例如,在标题"列中,如果有一个值"Good &
bad",则如何将其替换为"Good&不好"?
For example, in column Title if there is a value 'Good &
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 & bad', 'BB', 'CC', 'DD', 'Good & bad'],
'B': range(5),
'C': ['Good & bad'] * 5})
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 = df.replace('&','&', 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('&','&', 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
这篇关于如何使用 pandas 替换所有列中的所有字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文