如何替换 pandas 数据框的列中的文本? [英] How to replace text in a column of a Pandas dataframe?

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

问题描述

我的数据框中有这样的列:

I have a column in my dataframe like this:

range
"(2,30)"
"(50,290)"
"(400,1000)"
... 

,我想替换带有-破折号的逗号。我当前正在使用此方法,但未进行任何更改。

and I want to replace the , comma with - dash. I'm currently using this method but nothing is changed.

org_info_exc['range'].replace(',', '-', inplace=True)

有人可以帮忙吗?

推荐答案

使用矢量化的 str 方法 替换

Use the vectorised str method replace:

In [30]:

df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
      range
0    (2-30)
1  (50-290)

编辑

因此,如果我们查看您尝试过的内容以及为什么不这样做工作:

So if we look at what you tried and why it didn't work:

df['range'].replace(',','-',inplace=True)

来自文档中,我们看到了以下说明:

from the docs we see this desc:


str或regex:str:与to_replace完全匹配的字符串将用值替换

str or regex: str: string exactly matching to_replace will be replaced with value

所以因为str值不匹配,没有替换发生,请与以下内容进行比较:

So because the str values do not match, no replacement occurs, compare with the following:

In [43]:

df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0    (2,30)
1         -
Name: range, dtype: object

在这里,我们在第二行获得完全匹配,并且替换发生。

here we get an exact match on the second row and the replacement occurs.

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

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