Edward Edward - 3 months ago 33
Python Question

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?

Answer

@shx2 explains why this happens. But you can still do what you want — just forget the NaN and use Series.map:

import numpy as np
import pandas as pd

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}
df['a'] = df['a'].map(mapper)
print(df)

#      a
# 0  1.0
# 1  0.0
# 2  2.0
# 3  1.0
# 4  NaN
# 5  0.0
# 6  2.0

If you want to map the NaN entries to, say, 55, use .fillna():

df['a'] = df['a'].fillna(55)
print(df)

#       a
# 0   1.0
# 1   0.0
# 2   2.0
# 3   1.0
# 4  55.0
# 5   0.0
# 6   2.0
Comments