Search code examples
pythonnan

NaN in mapper - name 'nan' is not defined


I do as below

mapper = {'a': 'b', 'c': nan, 'd': 'e',  nan : nan}
df['b'] = [ mapper[x] for x in df['a'] ]
df['b'].value_counts()

and

NameError                                 Traceback (most recent call last)
<ipython-input-48-3862b2347ce7> in <module>()
NameError: name 'nan' is not defined

What's wrong? Is a mistake in coding or in file?


Solution

  • Python does not have a built-in name nan, nor is there a keyword.

    It looks as if you forgot to import it; numpy defines such a name:

    from numpy import nan
    

    From the local name df I infer you are probably using pandas; pandas' documentation usually uses np.nan, where np is the numpy module imported with import numpy as np. See their 10 Minute to pandas intro for example.

    Other options: