If you are working with Python and trying to use the numpy library, you may encounter the “NameError: name ‘numpy’ is not defined” error. In this tutorial, we will explore why this error occurs and the steps required to fix it such that your Python code can successfully run without errors.
We will cover common causes of the error and provide solutions to help you get your code up and running quickly. So, let’s get started!
Why does the NameError: name 'numpy' is not defined
error occur?
This error occurs when you try to use the numpy library in your Python code, but Python cannot find the numpy module in its namespace. The following are some of the scenarios in which this error usually occurs.
- You have not imported the numpy module.
- You have imported the numpy module using a different name.
Before we proceed with the above scenario and their solutions, make sure that you have the numpy
module installed. If numpy
is not installed and you try to import it, you’ll get a ModuleNotFoundError
. Alternatively, you can check if you have numpy installed by running pip list
in your terminal or command prompt. If numpy is not listed, install it by running pip install numpy
.
If you are using a virtual environment or a different Python environment, make sure numpy is installed in that environment. You can activate the environment and run pip list
to check if numpy is installed.
Let’s now look at the above scenarios in detail.
The numpy
module is not imported
It can happen that you are trying to use the numpy
module without even importing it. This is because Python does not recognize the numpy library and its functions until it is imported into the code.
For example, let’s try to use numpy
without importing it and see what we get.
# note that numpy is not imported # create an array ar = numpy.array([1, 2, 3, 4]) # print the array print(ar)
Output:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 4 1 # note that numpy is not imported 2 3 # create an array ----> 4 ar = numpy.array([1, 2, 3, 4]) 5 # print the array 6 print(ar) NameError: name 'numpy' is not defined
We get a NameError
stating that the name numpy
is not defined. To use numpy
, you need to import it first.
import numpy # create an array ar = numpy.array([1, 2, 3, 4]) # print the array print(ar)
Output:
[1 2 3 4]
Here, we are importing the numpy
module first and then using it. You can see that we did not get any errors here.
Note that generally people use the import numpy as np
statement to import the numpy module with the alias np
.
The numpy
module is imported using a different name
If you import the numpy module using a different name, for example import numpy as np
, and then try to use the name “numpy” to use it, you will get a NameError
because the name “numpy” is not defined in your current namespace.
Let’s look at an example.
import numpy as np # create an array ar = numpy.array([1, 2, 3, 4]) # print the array print(ar)
Output:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 4 1 import numpy as np 3 # create an array ----> 4 ar = numpy.array([1, 2, 3, 4]) 5 # print the array 6 print(ar) NameError: name 'numpy' is not defined
We get a NameError: name 'numpy' is not defined
. This is because we have imported the numpy
module with the name np
but we’re trying to use it using the name numpy
.
To fix this error, you can either access numpy using the name that you have used in the import statement or import numpy without an alias.
import numpy as np # create an array ar = np.array([1, 2, 3, 4]) # print the array print(ar)
Output:
[1 2 3 4]
In the above example, we are importing numpy
as np
and then using np
to access the numpy
module’s methods.
Alternatively, as seen in the example in the previous section, you can import numpy
without any aliases and simply use numpy
to avoid the NameError
.
How to fix the NameError: name 'np' is not defined
error?
You can similarly get the NameError: name 'np' is not defined
if you’ve not used np
as the name for numpy while importing it. For example.
import numpy # create an array ar = np.array([1, 2, 3, 4]) # print the array print(ar)
Output:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 4 1 import numpy 3 # create an array ----> 4 ar = np.array([1, 2, 3, 4]) 5 # print the array 6 print(ar) NameError: name 'np' is not defined
We get this error because the name np
does not exit in the namespace. To fix this error, use the import statement import numpy as np
.
import numpy as np # create an array ar = np.array([1, 2, 3, 4]) # print the array print(ar)
Output:
[1 2 3 4]
We don’t get an error now.
Conclusion
In conclusion, the “NameError: name ‘numpy’ is not defined” error can occur due to two scenarios – numpy is not imported or numpy is imported with a different name. If numpy is not imported, you can simply import it using the command import numpy
. On the other hand, if numpy is imported with a different name, for example, import numpy as np
you can use “np” to use numpy methods. By following these steps, you can easily fix the “NameError: name ‘numpy’ is not defined” error and continue with your computation tasks utilizing numpy.
You might also be interested in –
- How to Fix – NameError: name ‘pandas’ is not defined
- Find the shortest word in a List in Python (with examples)
- Count Unique Values in a Numpy Array
-
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts
Как исправить: имя NameError 'np' не определено
17 авг. 2022 г.
читать 2 мин
Одна из наиболее распространенных ошибок, с которыми вы можете столкнуться при использовании Python:
NameError : name 'np' is not defined
Эта ошибка возникает, когда вы импортируете библиотеку Python NumPy , но не можете указать псевдоним np при импорте.
В следующих примерах показано, как возникает эта проблема и как ее устранить.
Пример 1: импорт numpy
Предположим, вы импортируете библиотеку NumPy, используя следующий код:
import numpy
Если вы затем попытаетесь определить пустой массив значений, вы получите следующую ошибку:
#define numpy array
x = np.random.normal (loc=0, scale=1, size=20)
#attempt to print values in arrary
print(x)
Traceback (most recent call last):
----> 1 x = np.random.normal(loc=0, scale=1, size=20)
2 print(x)
NameError : name 'np' is not defined
Чтобы исправить эту ошибку, вам нужно указать псевдоним np при импорте NumPy:
import numpy as np
#define numpy array
x = np.random.normal (loc=0, scale=1, size=20)
#print values in arrary
print(x)
[-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484
0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984
-0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364
0.14647622 0.87787596]
Пример 2: импорт из numpy *
Предположим, вы импортируете все функции из библиотеки NumPy, используя следующий код:
from numpy import *
Если вы затем попытаетесь определить пустой массив значений, вы получите следующую ошибку:
#define numpy array
x = np.random.normal (loc=0, scale=1, size=20)
#attempt to print values in arrary
print(x)
Traceback (most recent call last):
----> 1 x = np.random.normal(loc=0, scale=1, size=20)
2 print(x)
NameError : name 'np' is not defined
Чтобы исправить эту ошибку, вам нужно указать псевдоним np при импорте NumPy:
import numpy as np
#define numpy array
x = np.random.normal (loc=0, scale=1, size=20)
#print values in arrary
print(x)
[-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484
0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984
-0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364
0.14647622 0.87787596]
Кроме того, вы можете вообще не использовать синтаксис np :
import numpy
#define numpy array
x = numpy. random.normal (loc=0, scale=1, size=20)
#print values in arrary
print(x)
[-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484
0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984
-0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364
0.14647622 0.87787596]
Примечание. Обычно используется синтаксис «импортировать numpy как np», поскольку он предлагает более лаконичный способ использования функций NumPy. Вместо того, чтобы каждый раз вводить «numpy», вы можете просто ввести «np», который быстрее и легче читается.
Дополнительные ресурсы
Как исправить: имя NameError ‘pd’ не определено
Как исправить: нет модуля с именем pandas
I am working on machine learning using «Python Deep Learning» by coding the examples to get a better understanding. I am trying to execute the code at the end of Ch. 3. Executing the code gives me a NameError: name 'numpy' is not defined.
The import numpy
line was not part of the original text from the book, so I added that line after I received the same error before adding the line. Initially, I supposed that one of the prior imports would have brought in numpy, but apparently I was incorrect. Anyway, isn’t the line supposed to handle that error?
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils import np_utils
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
classes = 100
Y_train = np_utils.to_categorical(Y_train, classes)
Y_test = np_utils.to_categorical(Y_test, classes)
input_size = 784
batch_size = 100
hidden_neurons = 100
epochs = 15
model = Sequential()
model.add(Dense(hidden_neurons, input_dim=input_size))
model.add(Activation('sigmoid'))
model.add(Dense(classes, input_dim=hidden_neurons))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'],
optimizer='sgd')
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=epochs, verbose=1)
score = model.evaluate(X_test, Y_test, verbose=1)
print('Test accuracy:', score[1])
weights = model.layers[0].get_weights()
w = weights[0].T
for neuron in range(hidden_neurons):
plt.imshow(numpy.reshape(w[neuron], (28, 28)), cmap = cm.Greys_r)
plt.show()
I get the following error:
Traceback (most recent call last):
File "MyPython.py", line 31, in <module>
plt.imshow(numpy.reshape(w[neuron], (28, 28)),
NameError: name 'numpy' is not defined
I don’t understand why and I don;t have an expected result for the plot (yet). I need to make the code work so I can start exploring the internals to get a better understanding about what is going on, because this is my first introduction to keras.
Table of Contents
Hide
- Solution NameError: name ‘np’ is not defined
- Method 1 – Importing NumPy with Alias as np
- Method 2 – Importing all the functions from NumPy
- Method 3 – Importing NumPy package without an alias
In Python, NameError: name ‘np’ is not defined occurs when you import the NumPy library but fail to provide the alias as np while importing it.
In this article, let us look at what is NameError name np is not defined and how to resolve this error with examples.
Let us take a simple example to reproduce this error. In the below example, we have imported the NumPy library and defined a NumPy array.
# import numpy library
import numpy
# define numpy array
array = np.array([[12, 33], [21, 45]])
# print values in array format
print(array)
Output
Traceback (most recent call last):
File "C:PersonalIJSCodemain.py", line 5, in <module>
array = np.array([[12, 33], [21, 45]])
NameError: name 'np' is not defined
When we run the code, we get NameError: name ‘np’ is not defined since we did not provide an alias while importing the NumPy library.
There are multiple ways to resolve this issue. Let us look at all the approaches to solve the NameError.
Method 1 – Importing NumPy with Alias as np
The simplest way to resolve this error is by providing an alias as np while importing the NumPy library. Let’s fix our code by providing an alias and see what happens.
# import numpy library
import numpy as np
# define numpy array
array = np.array([[12, 33], [21, 45]])
# print values in array format
print(array)
Output
[[12 33]
[21 45]]
The syntax “import numpy as np
” is commonly used because it offers a more concise way to call NumPy functions, and the code is more readable as we do not have to type “numpy
” each time.
Method 2 – Importing all the functions from NumPy
There might be a situation where you need to import all the functions from the NumPy library, and to do that, we will be using the below syntax.
from numpy import *
In this case, you do not need any reference to call any functions of NumPy. You can directly call the methods without using an alias, as shown below.
# import numpy library
from numpy import *
# define numpy array
array = array([[12, 33], [21, 45]])
# print values in array format
print(array)
Output
[[12 33]
[21 45]]
Method 3 – Importing NumPy package without an alias
Another way is to import a complete NumPy package and call the functions directly with the NumPy name without defining an alias.
# import numpy library
import numpy
# define numpy array
array = numpy.array([[12, 33], [21, 45]])
# print values in array format
print(array)
Output
[[12 33]
[21 45]]
In the above example, we import the complete NumPy library and use numpy.array()
method to create an array.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
In this article, we will discuss how to fix NameError np that is not defined in Python.
When we imported the NumPy module without alias and used np in the code, the error comes up.
Example: Code to depict error
Python3
import
numpy
a
=
np.array([
1
,
2
,
3
,
45
])
a
Output:
name 'np' is not defined
Here np is an alias of the NumPy module so we can either import the NumPy module with the alias or import NumPy without the alias and use the name directly.
Method 1: By using the alias when importing the numpy
We can use an alias at the time of import to resolve the error.
Syntax:
import numpy as np
Example: Program to import numpy as alias
Python3
import
numpy as np
a
=
np.array([
1
,
2
,
3
,
45
])
a
Output:
array([ 1, 2, 3, 45])
Method 2: Using NumPy directly
We can use NumPy module directly to use in a data structure.
Syntax:
import numpy
Example: Using NumPy directly
Python3
import
numpy
a
=
numpy.array([
1
,
2
,
3
,
45
])
a
Output:
array([ 1, 2, 3, 45])
Last Updated :
28 Nov, 2021
Like Article
Save Article