简体   繁体   中英

Convert string decimal numbers in column to float in a Pandas DataFrame

I have a dataset like this (with many more columns):

      FLAG__DC SEXECOND CRM_TAUX
0            N        M      0,9
1            N        M      0,9
2            N        M      1,2
3            O        M        1
4            N        M        1
5            N        M      0,9
6            O        M        1
7            N        M      0,9

I want to convert the column CRM_TAUX to Float... Please help!

I have tried this but doesn't work:

df['CRM_TAUX'] = df.CRM_TAUX.replace(',','.')
df['CRM_TAUX'] = df.CRM_TAUX.apply(pd.to_numeric)

This is the error I get (and many more):

Unable to parse string "1,2" at position 0

Thanks in advance!

Use str.replace

df.CRM_TAUX.str.replace(',' , '.')

Out[2246]:
0    0.9
1    0.9
2    1.2
3      1
4      1
5    0.9
6      1
7    0.9
Name: CRM_TAUX, dtype: object

Next, call pd.to_numeric on it should work

s = df.CRM_TAUX.str.replace(',' , '.')
df['CRM_TAUX'] = pd.to_numeric(s)


Out[2250]:
  FLAG__DC SEXECOND  CRM_TAUX
0        N        M       0.9
1        N        M       0.9
2        N        M       1.2
3        O        M       1.0
4        N        M       1.0
5        N        M       0.9
6        O        M       1.0
7        N        M       0.9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM