I do as below
import numpy as np
from numpy import nan
df = pd.DataFrame({'a':[1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0, nan : nan}
df['a'] = [ mapper[x] for x in df['a'] ]
and
KeyError: nan
I tried to change dtypes
df['a'] = df['a'].astype(object)
but again
KeyError: nan
what's wrong?
We can replace NaN values with 0 to get rid of NaN values. This is done by using fillna() function. This function will check the NaN values in the dataframe columns and fill the given value.
How to Fix KeyError in Python. To avoid the KeyError in Python, keys in a dictionary should be checked before using them to retrieve items. This will help ensure that the key exists in the dictionary and is only used if it does, thereby avoiding the KeyError . This can be done using the in keyword.
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float.
The problem is that nan is "not a number", and as such it equals no other number, not even another nan. You can read more about it here.
To demonstrate:
from numpy import nan
nan == nan
=> False
From this it must follow that nan is not in your dict, because it doesn't equal any of the keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With