NaN in mapper - name 'nan' is not defined
Asked Answered
P

3

17

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?

Prase answered 30/7, 2016 at 10:8 Comment(0)
D
41

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.

Dunnite answered 30/7, 2016 at 10:10 Comment(0)
T
1

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.

Trefor answered 30/7, 2016 at 10:9 Comment(0)
D
0

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

Dorseydorsiferous answered 3/9, 2022 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.