Fix: NameError name ‘np’ is not defined?


One of the most common errors you may encounter when using Python is:

NameError: name 'np' is not defined

This error occurs when you import the python library , but fail to give it the alias of np when importing it.

The following examples illustrate how this problem occurs and how to fix it.

Example 1: import numpy

Suppose you import the NumPy library using the following code:

import numpy

If you then attempt to define a numpy array of values, you’ll get the following error:

#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

To fix this error, you need provide the alias of np when importing 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]

Example 2: from numpy import *

Suppose you import all functions from the NumPy library using the following code:

from numpy import *

If you then attempt to define a numpy array of values, you’ll get the following error:

#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

To fix this error, you need provide the alias of np when importing 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]

Alternatively, you can choose to not use the np syntax at all:

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]

Note: The syntax “import numpy as np” is commonly used because it offers a more concise way to use NumPy functions. Instead of typing “numpy” each time, you can simply type in “np” which is quicker and easier to read.

x