NaN in mapper – name 'nan' is not defined

Question:

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?

Asked By: Edward

||

Answers:

You didn’t define what the variable nan is, so Python raises a NameError. If you want to check whether a number is NaN (not a number), use math.isnan(x), where x is a float.

Answered By: Aurora0001

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.

Answered By: Martijn Pieters

I had a similar case, maybe the same. I didn’t import or qualify nan, but np automatically translated None to nan in my matrix output.
I could either just use None and let numpy figure it out or import nan from numpy, I didn’t know where nan was in numpy, so i just used None and it worked. Possibly the better choice is to import numpy’s nan- idk

Answered By: Steve Strongheart
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.