Join my Laravel for REST API's course on Udemy 👀

Solve `NameError: name 'np' is not defined` in Python

May 12, 2022  ‐ 1 min read

If you came across the error message "NameError: name 'np' is not defined" you probably try to call a numpy function. The numpy package is often abbreviated to np in its import statement.

See the following piece of code for example, it tries to call the .abs() function on np. However, np is not defined in the scope of our Python script

import numpy

print(np.abs(-4))
# => NameError: name 'np' is not defined

Instead you could call the .abs() function on the numpy module as intended.

import numpy

print(numpy.abs(-4))
# => 4

But the answer your are most likely looking for is the following, where you import the numpy module under a different name: np.

import numpy as np

print(np.abs(-4))
# => 4