3

How can I convert one string column to float considering that it contains N/A values? I've tried to use the to_numeric function, but I'm receiving an error: "Unable to parse string "N/A" at position.

6
  • Are you talking about a column in a pandas dataframe? Commented Feb 4, 2022 at 15:15
  • Use an if condition. Check if the value is not NA then do the conversion. Commented Feb 4, 2022 at 15:16
  • if pandas, something like: np.where(df["your column"].isna() is False, df["your column"], df["your column"].astype(float)) Commented Feb 4, 2022 at 15:19
  • Yes, pandas. I've tried this code, but it also results in an error "could not convert string to float: 'N/A' Commented Feb 4, 2022 at 15:24
  • oh it's a string, then just: df["your column"].replace("N/A", np.nan).astype(float) Commented Feb 4, 2022 at 15:32

1 Answer 1

6

The solution that worked in my case was to add an argument errors='coerce' to the to_numeric function.

df["mycolumn"] = pd.to_numeric(df["mycolumn"], errors='coerce', downcast="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.