Last modified: Mar 06, 2025 By Alexander Williams

Fix Python NameError: Name 'np' Not Defined

Python is a powerful programming language. But errors like NameError: Name 'np' Not Defined can be frustrating. This article explains how to fix it.

What is the NameError: Name 'np' Not Defined?

The error occurs when Python cannot find the name np. This usually happens when you forget to import the numpy library.

Common Causes of the Error

There are a few common reasons why this error occurs:

  • You forgot to import numpy.
  • You misspelled the import statement.
  • You are using np before importing it.

How to Fix the Error

To fix the error, you need to import the numpy library correctly. Here’s how:


    # Correct way to import numpy
    import numpy as np
    

After importing, you can use np without any issues. For example:


    # Example usage of numpy
    import numpy as np
    array = np.array([1, 2, 3])
    print(array)
    

    # Output
    [1 2 3]
    

Best Practices to Avoid the Error

Here are some tips to avoid this error in the future:

  • Always import libraries at the top of your script.
  • Double-check the spelling of the import statement.
  • Use an IDE that highlights errors in real-time.

If you encounter similar errors like NameError: Name 'pd' Not Defined or NameError: Name 'json' Not Defined, the solutions are similar.

Conclusion

The NameError: Name 'np' Not Defined is a common error in Python. It happens when you forget to import the numpy library. By following the steps above, you can easily fix it.