Convert string number columns to float in Pandas

ahbon :

I would like to convert price1 and price2 from the following dataframe to float type:

   id         price1        price2
0   1    9,771,338.7           NaN
1   2      9,734,256           NaN
2   3      3,331,766     2,391,766
3   4      2,414,571     1,856,571
4   5     725,031.33           NaN
5   6   1,530,519.75  1,392,519.75
6   7   4,655,184.06           NaN
7   8    9,864,973.6   8,224,973.6
8   9  14,599,046.08  9,514,046.08
9  10   2,075,439.87  1,259,439.87

My first solution:

price_cols = ['price1', 'price2']
df[price_cols] = df[price_cols].astype(float)

Out:

ValueError: could not convert string to float: '9,771,338.7'

My second solution:

df[price_cols] = df[price_cols].apply(pd.to_numeric, errors='coerce')

Out:

   id  price1  price2
0   1     NaN     NaN
1   2     NaN     NaN
2   3     NaN     NaN
3   4     NaN     NaN
4   5     NaN     NaN
5   6     NaN     NaN
6   7     NaN     NaN
7   8     NaN     NaN
8   9     NaN     NaN
9  10     NaN     NaN

How could I convert those columns correctly? Thanks.

mrzo :

Your columns contain commas which are not parseable to floats. Just remove them from the string before converting them to floats.

df['price1'] = df['price1'].str.replace(',', '').astype(float)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169273&siteId=1