2

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.

3
  • 1
    df.set_index("id").replace(",","",regex=True).astype(float)? Commented Mar 9, 2020 at 3:39
  • 2
    If you read your data from a csv, tsv or excel file, you can pass thousands=','. Commented Mar 9, 2020 at 3:46
  • Just tested, both the solutions you proposed work out. Commented Mar 9, 2020 at 4:17

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.