'How to replace text in a string 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?



Solution 1:[1]

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

Solution 2:[2]

Replace all commas with underscore in the column names

data.columns= data.columns.str.replace(' ','_',regex=True)

Solution 3:[3]

If you only need to replace characters in one specific column, somehow regex=True and in place=True all failed, I think this way will work:

data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))

lambda is more like a function that works like a for loop in this scenario. x here represents every one of the entries in the current column.

The only thing you need to do is to change the "column_name", "characters_need_to_replace" and "new_characters".

Solution 4:[4]

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

Solution 5:[5]

Almost similar to the answer by Nancy K, this works for me:

data["column_name"] = data["column_name"].apply(lambda x: x.str.replace("characters_need_to_replace", "new_characters"))

Solution 6:[6]

If you want to remove two or more elements from a string, example the characters '$' and ',' :

Column_Name
===========
$100,000
$1,100,000

... then use:

data.Column_Name.str.replace("[$,]", "", regex=True)

=> [ 100000, 1100000 ]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kevcisme
Solution 2 adiga
Solution 3 Nancy K
Solution 4 cdutra
Solution 5 Freddie
Solution 6 smci