0

I have a dataframe and one column Quantity has the below values

Col1
20,000
20
-10,000
-50

I want to convert this column to a float, as later I am doing a comparison with a floating number to filter some rows. However I get some or the other error: "Can only use .str accessor with string values!"

I think I found the issue, when it reads the value "-50", it reads it as a float, so no "str" accessor is valid. While loading the csv file the column is an object type series

my code looks like

df['Qty'] = np.where(~df['Qty'].str.contains(','),df['Qty'],df['Qty'].str.replace(",",""))
df['Qty'] = df['Qty'].astype(float)

How can I resolve this issue?
5
  • Use pd.to_numeric Commented Feb 11, 2020 at 15:58
  • if I do to_numeric I get the error "ValueError: Unable to parse string "20,000" at position 0". @yatu Commented Feb 11, 2020 at 16:05
  • pd.to_numeric(series, errors='coerce') Commented Feb 11, 2020 at 16:08
  • Can you share the code for loading the CSV? The dtype can be selected there. Commented Feb 11, 2020 at 16:12
  • 1
    Does this answer your question? Convert Pandas Dataframe to Float with commas and negative numbers Commented Feb 11, 2020 at 16:16

1 Answer 1

1

This will do the work:

pd.to_numeric(df['Col1'].astype(str).str.replace(',',''))
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.