How to convert a string in float with a space - pandas

Viewed 3784

When I import an excel, the numbers of a column are not in float and some are. How can I convert all to float? The space is causing me problems.

  df['column']:
             column
0          3 000,00                
1            156.00
2                 0

I am trying:

df['column'] = df['column'].str.replace(' ','')

but it's not working. I would do after .astype(float), but cant get there. Any solutions? [1] is already a float, but [0] is a string.

2 Answers

Just cast them all as a string first:

df['column'] = [float(str(val).replace(' ','').replace(',','.')) for val in df['column'].values]

Example:

>>> df = pd.DataFrame({'column':['3 000,00', 156.00, 0]})
>>> df['column2'] = [float(str(val).replace(' ','').replace(',','.')) for val in df['column'].values]
>>> df
     column  column2
0  3 000,00   3000.0
1       156    156.0
2         0      0.0
import re    
df['column'] = df['column'].apply(lambda x: re.sub("[^0-9.]", "", str(x).replace(',','.'))).astype(float)
Related