Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

Can anybody help?

like image 552
UserYmY Avatar asked Oct 07 '22 09:10

UserYmY


1 Answers

Use the vectorised str method replace:

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

df
      range
0    (2-30)
1  (50-290)

EDIT: 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 description:

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

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

df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)

df['range']

0    (2,30)
1         -
Name: range, dtype: object

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

like image 393
EdChum Avatar answered Oct 24 '22 05:10

EdChum