替换 pandas 数据帧中所有出现的字符串(Python) [英] Replace all occurrences of a string in a pandas dataframe (Python)
本文介绍了替换 pandas 数据帧中所有出现的字符串(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大约有 20 列的 Pandas 数据框.
可以通过手动写入所有列名来替换所有出现的字符串(这里是换行符):
df['columnname1'] = df['columnname1'].str.replace("
","
")df['columnname2'] = df['columnname2'].str.replace("
","
")df['columnname3'] = df['columnname3'].str.replace("
","
")...df['columnname20'] = df['columnname20'].str.replace("
","
")
不幸的是这不起作用:
df = df.replace("
","
")
还有其他更优雅的解决方案吗?
解决方案
您可以使用 replace
并将字符串传递给 find/replace 作为字典键/项目:
df.replace({'
': '
'}, regex=True)
例如:
<预><代码>>>>df = pd.DataFrame({'a': ['1 ', '2 ', '3'], 'b': ['4 ', '5', '6 ']})>>>df乙0 1 4 1 2 52 3 6 >>>df.replace({' ': ''}, regex=True)乙0 1 br4
1 2 br>52 3 6 6
I have a pandas dataframe with about 20 columns.
It is possible to replace all occurrences of a string (here a newline) by manually writing all column names:
df['columnname1'] = df['columnname1'].str.replace("
","<br>")
df['columnname2'] = df['columnname2'].str.replace("
","<br>")
df['columnname3'] = df['columnname3'].str.replace("
","<br>")
...
df['columnname20'] = df['columnname20'].str.replace("
","<br>")
This unfortunately does not work:
df = df.replace("
","<br>")
Is there any other, more elegant solution?
解决方案
You can use replace
and pass the strings to find/replace as dictionary keys/items:
df.replace({'
': '<br>'}, regex=True)
For example:
>>> df = pd.DataFrame({'a': ['1
', '2
', '3'], 'b': ['4
', '5', '6
']})
>>> df
a b
0 1
4
1 2
5
2 3 6
>>> df.replace({'
': '<br>'}, regex=True)
a b
0 1<br> 4<br>
1 2<br> 5
2 3 6<br>
这篇关于替换 pandas 数据帧中所有出现的字符串(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文