5

My question is similar to this one.

I want to convert all the values in the dataframe to float type. But what is need more is to ignore the rows where such conversions cannot happen.

For example, given a string '0.9', it will be converted to float successfully but a string like 'why' will through an error. I want to remove all such rows in the dataframe which would come under the error case.

silent_dev
  • 1,566
  • 3
  • 20
  • 45
  • Why does that linked question not do what you want here? It already has an answer with `errors='ignore'` which should do what you want – EdChum Jun 05 '17 at 13:00
  • I used it but not working. When I do this to a DF colum : `sum(list(df[col]))`, it throws an error saying - `TypeError: unsupported operand type(s) for +: 'int' and 'str' ` – silent_dev Jun 05 '17 at 13:02
  • Please post raw data, code to reproduce your df, your attempts at converting, the desired output and any errors as your question is short of details as you're asking about conversion but then commenting about your desired result – EdChum Jun 05 '17 at 13:03

1 Answers1

9

Try this:

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

From docs:

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

If ‘raise’, then invalid parsing will raise an exception

If ‘coerce’, then invalid parsing will be set as NaN

If ‘ignore’, then invalid parsing will return the input

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419