替换大 pandas 数据框中所有出现的字符串(Python) [英] Replace all occurrences of a string in a pandas dataframe (Python)

查看:223
本文介绍了替换大 pandas 数据框中所有出现的字符串(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约20列的熊猫数据框。

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("\n","<br>")
df['columnname2'] = df['columnname2'].str.replace("\n","<br>")
df['columnname3'] = df['columnname3'].str.replace("\n","<br>")
...
df['columnname20'] = df['columnname20'].str.replace("\n","<br>")

工作:

df = df.replace("\n","<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({'\n': '<br>'}, regex=True)

例如:

>>> df = pd.DataFrame({'a': ['1\n', '2\n', '3'], 'b': ['4\n', '5', '6\n']})
>>> df
   a    b
0  1\n  4\n
1  2\n  5
2  3    6\n

>>> df.replace({'\n': '<br>'}, regex=True)
   a      b
0  1<br>  4<br>
1  2<br>  5
2  3      6<br>

这篇关于替换大 pandas 数据框中所有出现的字符串(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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