Reputation: 95
While converting my object type columns to Float type, all my values are turned to Nan.
I checked the dtype of columns post conversion which shows all are float type. Hence succesful in that regard. But Why does it produces Nan values.
This is the code I'm using. Both versions of code below are producing same results.
data.M0=pd.to_numeric(data.M0, errors='coerce')
data['M1'] = data['M1'].apply(pd.to_numeric, downcast='float', errors='coerce')
Upvotes: 1
Views: 831
Reputation: 71560
pd.to_numeric
has an errors
argument which can be ignore
, raise
and coerce
.
coerce
sets to NaN
if the values aren't numeric-like values.
As mentioned in the [docs]9https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html).
If ‘coerce’, then invalid parsing will be set as
NaN
.
Upvotes: 0
Reputation: 23217
pd.to_numeric
with parameter errors='coerce'
returns NaN
with invalid parsing for entries that can't be converted to float values:
Official document states that:
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.
Probably, your elements in the dataframe are non-numeric and can't be converted.
Upvotes: 3