If you are running some python code and stuck here (Nameerror name np is not defined). This article will explain step by step fix for this error. So let’s see.
Nameerror name np is not defined: Reason
When you import the NumPy python package. You may import it with or without aliases. For example –
#numpy without alias import numpy array = numpy.array([[23, 87], [31, 49]]) print(array)
We can also define an alias for NumPy. Usually, NumPy is imported by np alias.
#numpy with alias np import numpy as np array = np.array([[23, 87], [31, 49]]) print(array)
But when we do not define NumPy alias or define with a different name. And while calling you to use np as a NumPy reference. You will get the same error. Like below-
import numpy as npy array = np.array([[23, 87], [31, 49]]) print(array)
Here we have import NumPy as alias npy. But while array creation we used np as an alias in the place of npy and we got the same error.
Nameerror name np is not defined: Solution –
1. Import the package Numpy without any reference –
In this solution, you should import a complete NumPy package and remove its reference, and direct call with NumPy name.
import numpy array = numpy.array([[87, 81], [31, 59]]) print(array)
2.Change the define statement
If you are not opting for solution one. You may correct the alias of NumPy while calling in syn of defining it. use the below code –
import numpy as np
Please make sure you are using np everywhere while calling.
3. Use from numpy import *
Here you do not need any object or reference while calling any function of the NumPy module. Please refer to the below code.
from numpy import * array = array([[87, 81], [31, 59]]) print(array)
Once we run the above code we get the same output.
Well, I hope this article must have clear all you doubt. I usually found this issue when we merge code from two different sources. We encountered this error. Anyway, Do not forget to give your feedback in the comment section.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.