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

查看:77
本文介绍了如何替换 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)

来自 docs 我们看到了这个说明:

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天全站免登陆