Christian Singer Christian Singer - 2 months ago 14
Python Question

Pandas: substitute commas for points in a column

I have a column of values from a csv-file who contain commas instead of points. With the code below I want to turn these into points, however this does not work.

There is no error message, the code just runs and if I call the column

Betrag()
(german: absolute value) from the datafram
Umsatz
, it display no change. The commas are still in place.

def removecom(value):
value=value.replace(',','.')

Umsatz['Betrag()']=Umsatz['Betrag()'].apply(lambda value: removecom(value))

Umsatz['Betrag()']


for instance turn 7,99 into 7.99

Answer Source

The reason you see no change is because removecom returns nothing. You should return a value from the function like this:

def removecom(value):
    return value.replace(',','.')

However, a better method I would recommend is using df.str.replace:

Umsatz['Betrag()'] = Umsatz['Betrag()'].str.replace(',', '.')

Demo:

In [750]: df
Out[750]: 
      Col1
0  foo,bar
1  abc,def

In [751]: df['Col1'] = df.Col1.str.replace(',', '.')

In [752]: df
Out[752]: 
      Col1
0  foo.bar
1  abc.def