Solve the name ‘np’ is not defined name error
To fix this error, make sure to import the NumPy data analysis package into your notebook or script and optionally assign it the alias np, before calling any NumPy functionality in your Python code. Here’s an example:
import numpy as np
#call the NumPy library here
my_array = np.array ([165, 189, 205])
Reproducing the np not defined error in Python
If we call the NumPy library functions without importing the library first or assigning it the alias np , we will get a NameError.
Assume that you have written the following Python snippet:
import numpy #we purposely didn't assign the np alias.
#call the NumPy library here
my_array = np.array ([165, 189, 205])
This will invoke the following Name error (screenshot from Jupyter notebooks, but same one in PyCharm, VS Code, Spyder and Colab.
Fix the np not defined exception
Luckily, fixing this error is relatively easy. You need to complete the stwo steps below:
- Make sure to import the NumPy library into your Data Analysis dev environment.
- Make sure to assign the np alias to the NumPy library, so you can invoke it more easily.
So in a nutshell here’s your code:
import numpy as np # imported NumPy and assign it an alias for simplicity
#call the NumPy library here
my_array = np.array ([165, 189, 205])
Solve the modulenotfound error for NumPy
A somewhat related error occurs when you try to import NumPy into your JuPyter Notebook, but you have not previously installed it on your development environment first. If this is your case, you might want to look into our tutorial on fixing the no module found NumPy in Python.