如何替换 Pandas 数据框列中的文本? [英] How to replace text in a column of a Pandas dataframe?
问题描述
我的数据框中有一列像这样:
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)
有人可以帮忙吗?
推荐答案
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 or 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屋!