Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError: nan in dict

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?

like image 314
Edward Avatar asked Aug 12 '16 22:08

Edward


People also ask

How do I fix NaN in Python?

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 do I fix KeyError in Python?

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.

What is NaN in dictionary python?

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.


1 Answers

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.

like image 178
shx2 Avatar answered Oct 16 '22 08:10

shx2