In this tutorial, we'll see how to solve a common Pandas error:

NameError: name 'nan' is not defined

or

UndefinedVariableError: name 'nan' is not defined

We get this error from the Pandas or Python when numpy is not imported as a library.

1. import numpy nan

By default numpy should be installed with Pandas. So to solve the error we need to import numpy NaN value we can use:

from numpy import nan
× Note that
NaN
are aliases of
nan
.

The error is common for map operation in Pandas.

mp = {'K':' * 10**3', 'M':' * 10**6', '< ': ''}
df['amount'] = pd.eval(df['amount'].replace(mp.keys(), mp.values(), regex=True).str.replace(r'[^\d\.\*]+',''))

The example above will result into:

UndefinedVariableError: name 'nan' is not defined

2. import numpy library

As alternative we can import the whole library or other parts from numpy:

import numpy as np

This is described in: 10 minutes to pandas

3. install numpy

Finally if you need to install numpy library you can do it by:

pip install numpy