Home > Mobile >  How to replace all instances of a certain character in pandas dataframe
How to replace all instances of a certain character in pandas dataframe

Time:09-26

I have a huge data that TextEditors have difficulty to work. For illustration, I am just sharing a simple example given below:

  W1       W2      W3
71,65   833,06   54,955
21,63   131,21   32,90
11,56   23,60    87,55
13,21   93,06    14,05

I am trying to replace "," with "." to get output given below:

  W1       W2      W3
71.65   833.06   54.955
21.63   131.21   32.90
11.56   23.60    87.55
13.21   93.06    14.05

How can I get this output with python?

CodePudding user response:

You may try using replace on the entire data frame:

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

CodePudding user response:

If you do not want them to become floats then use

df.applymap(lambda x: x.replace(",", "."))

otherwise, if you want them to become floats then use
df.applymap(lambda x: x.replace(",", "."))

CodePudding user response:

Try apply:

>>> df.apply(lambda x: x.str.replace(',', '.')).astype(float)
      W1      W2      W3
0  71.65  833.06  54.955
1  21.63  131.21  32.900
2  11.56   23.60  87.550
3  13.21   93.06  14.050
>>> 

Or applymap to map value by value:

>>> df.applymap(lambda x: x.replace(',', '.')).astype(float)
      W1      W2      W3
0  71.65  833.06  54.955
1  21.63  131.21  32.900
2  11.56   23.60  87.550
3  13.21   93.06  14.050
>>> 
  • Related