Import numpy as np python ошибка

I have a very similar question to this question, but I am still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.

I installed NumPy following this link — as suggested in the question. The installation went fine but when I execute

import numpy

I got the following error:

Import error: No module named numpy

Peter Mortensen's user avatar

asked Oct 19, 2011 at 8:54

Seb's user avatar

4

You can simply use

pip install numpy

Or for python3, use

pip3 install numpy

Daniel Patru's user avatar

answered Feb 18, 2016 at 8:51

Andrei Madalin Butnaru's user avatar

12

Installing Numpy on Windows

  1. Open Windows command prompt with administrator privileges (quick method: Press the Windows key. Type «cmd». Right-click on the
    suggested «Command Prompt» and select «Run as Administrator)
  2. Navigate to the Python installation directory’s Scripts folder using the «cd» (change directory) command. e.g. «cd C:\Program Files (x86)\PythonXX\Scripts»

This might be: C:\Users\\AppData\Local\Programs\Python\PythonXX\Scripts or C:\Program Files (x86)\PythonXX\Scripts (where XX represents the Python version number), depending on where it was installed. It may be easier to find the folder using Windows explorer, and then paste or type the address from the Explorer address bar into the command prompt.

  1. Enter the following command: «pip install numpy».

You should see something similar to the following text appear as the package is downloaded and installed.

Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)  
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3

MechtEngineer's user avatar

answered Nov 13, 2017 at 3:10

harshitha yendapally's user avatar

I think there are something wrong with the installation of numpy.
Here are my steps to solve this problem.

  1. go to this website to download correct package: http://sourceforge.net/projects/numpy/files/
  2. unzip the package
  3. go to the document
  4. use this command to install numpy: python setup.py install

legoscia's user avatar

legoscia

39.7k22 gold badges116 silver badges167 bronze badges

answered Dec 9, 2013 at 15:49

Haimei's user avatar

HaimeiHaimei

12.6k3 gold badges50 silver badges36 bronze badges

1

I also had this problem (Import Error: No module named numpy) but in my case it was a problem with my PATH variables in Mac OS X. I had made an earlier edit to my .bash_profile file that caused the paths for my Anaconda installation (and others) to not be added properly.

Just adding this comment to the list here in case other people like me come to this page with the same error message and have the same problem as I had.

Mamad Farrahi's user avatar

answered May 2, 2015 at 18:17

Bill's user avatar

BillBill

10.4k10 gold badges62 silver badges86 bronze badges

2

You can try:

py -3 -m  pip install anyPackageName

In your case use:

py -3 -m  pip install numpy

vvvvv's user avatar

vvvvv

25.7k19 gold badges49 silver badges81 bronze badges

answered Sep 14, 2019 at 5:14

Clinton Roy's user avatar

Clinton RoyClinton Roy

2,6792 gold badges10 silver badges7 bronze badges

1

You should try to install numpy using one of those:

pip install numpy
pip2 install numpy
pip3 install numpy

For some reason in my case pip2 solved the problem

answered Feb 13, 2020 at 20:16

Ateik's user avatar

AteikAteik

2,4584 gold badges39 silver badges59 bronze badges

Faced with same issue

ImportError: No module named numpy

So, in our case (we are use PIP and python 2.7) the solution was SPLIT pip install commands :

From

RUN pip install numpy scipy pandas sklearn

TO

RUN pip install numpy scipy
RUN pip install pandas sklearn

Solution found here : https://github.com/pandas-dev/pandas/issues/25193, it’s related latest update of pandas to v0.24.0

answered Feb 12, 2019 at 13:39

Nigrimmist's user avatar

NigrimmistNigrimmist

10.4k4 gold badges52 silver badges53 bronze badges

1

I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!

answered Mar 15, 2012 at 20:54

Chet's user avatar

ChetChet

21.4k10 gold badges40 silver badges58 bronze badges

I had numpy installed on the same environment both by pip and by conda, and simply removing and reinstalling either was not enough.

I had to reinstall both.

I don’t know why it suddenly happened, but the solution was

pip uninstall numpy

conda uninstall numpy

uninstalling from conda also removed torch and torchvision.

then

conda install pytorch-cpu torchvision-cpu -c pytorch

and

pip install numpy

this resolved the issue for me.

answered Dec 22, 2018 at 12:56

Gulzar's user avatar

GulzarGulzar

23.7k27 gold badges116 silver badges205 bronze badges

1

I too faced the above problem with phyton 3 while setting up python for machine learning.

I followed the below steps :-

Install python-2.7.13.msi

• set PATH=C:\Python27

• set PATH=C:\Python27\Scripts

Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Downloaded:- — numpy-1.13.1+mkl-cp27-cp27m-win32.whl

          --scipy-0.18.0-cp27-cp27m-win32.whl 

Installing numpy:
pip install numpy-1.13.1+mkl-cp27-cp27m-win32.whl

Installing scipy:
pip install scipy-0.18.0-cp27-cp27m-win32.whl

You can test the correctness using below cmds:-

>>> import numpy
>>> import scipy
>>> import sklearn
>>> numpy.version.version
'1.13.1'
>>> scipy.version.version
'0.19.1'
>>>

answered Sep 27, 2017 at 5:58

Vikram S's user avatar

Vikram SVikram S

5515 silver badges5 bronze badges

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy

answered Jul 29, 2019 at 19:05

georgeos's user avatar

georgeosgeorgeos

2,3512 gold badges24 silver badges28 bronze badges

0

I’m not sure exactly why I was getting the error, but pip3 uninstall numpy then pip3 install numpy resolved the issue for me.

answered Feb 25, 2017 at 14:12

Clay H's user avatar

Clay HClay H

6519 silver badges21 bronze badges

1

Those who are using xonsh, do xpip install numpy.

answered Feb 15, 2018 at 4:36

Necktwi's user avatar

NecktwiNecktwi

2,5137 gold badges39 silver badges63 bronze badges

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

answered Nov 1, 2017 at 4:32

Rashmi Nagpal's user avatar

import numpy as np
ImportError: No module named numpy 

I got this even though I knew numpy was installed and unsuccessfully tried all the advice above. The fix for me was to remove the as np and directly refer to modules . (python 3.4.8 on Centos)
.

import numpy
DataTwo=numpy.stack((OutputListUnixTwo))...

answered Jun 29, 2018 at 12:35

zzapper's user avatar

zzapperzzapper

4,7435 gold badges48 silver badges45 bronze badges

For me, on windows 10, I had unknowingly installed multiple python versions (One from PyCharm IDE and another from Windows store). I uninstalled the one from windows Store and just to be thorough, uninstalled numpy pip uninstall numpy and then installed it again pip install numpy. It worked in the terminal in PyCharm and also in command prompt.

answered May 15, 2020 at 4:07

Shubhzgang's user avatar

ShubhzgangShubhzgang

3222 silver badges9 bronze badges

this is the problem of the numpy’s version, please check out $CAFFE_ROOT/python/requirement.txt. Then exec: sudo apt-get install python-numpy>=x.x.x, this problem will be sloved.

answered May 11, 2016 at 15:18

zhangyi's user avatar

1

I did everything from the answers here but nothing worked. So I deleted all the previous installations of numpy using the commands below.

sudo rm -rf /usr/lib/python3/dist-packages/numpy*
sudo rm -rf /usr/lib/python3.7/dist-packages/numpy*
sudo rm -rf /usr/lib/python2.7/dist-packages/numpy*

Then just install using pip3.

sudo pip3 install numpy

Dharman's user avatar

Dharman

31.1k25 gold badges86 silver badges137 bronze badges

answered Apr 28, 2021 at 9:11

Noman's user avatar

NomanNoman

215 bronze badges

Run

conda update --all

PS recall calling python using either «python2» or «python3» (not merely «python»).

answered Oct 18, 2021 at 5:16

Itamar cohen's user avatar

solution for me — I installed numpy inside a virtual environment, but then running ipython was not inside virtual env:

(venv) ➜  which python
/Users/alon/code/google_photos_project/venv/bin/python
(venv) ➜  which ipython
/usr/bin/ipython

so I had to install ipython, and run ipython from the venv like this:

python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'

answered Aug 26, 2020 at 3:33

Alon Gouldman's user avatar

I was trying to use NumPy in Intellij but was facing the same issue so, I figured out that NumPy also comes with pandas. So, I installed pandas with IntelliJ tip and later on was able to import NumPy. Might help someone someday!

answered Aug 31, 2020 at 8:38

whatsinthename's user avatar

As stated in other answers, this error may refer to using the wrong python version. In my case, my environment is Windows 10 + Cygwin. In my Windows environment variables, the PATH points to C:\Python38 which is correct, but when I run my command like this:

./my_script.py

I got the ImportError: No module named numpy because the version used in this case is Cygwin’s own Python version even if PATH environment variable is correct.
All I needed was to run the script like this:

py my_script.py

And this way the problem was solved.

answered Sep 4, 2020 at 23:26

Metafaniel's user avatar

MetafanielMetafaniel

29.4k8 gold badges40 silver badges67 bronze badges

Try uninstalling and then reinstalling the Python extension for VSCode.

I tried many different solutions, but this «hard refresh» was the only one that worked for me.

answered Apr 14, 2021 at 10:48

Ole August Støle's user avatar

I just had the same problem as well! It turns out the problem happens when you’re installing Numpy to a version of python and trying to run the program using another python version. Probably the global version of Python your text editor opens by default is different from the one that you need for the version of numpy you are running.

So to start off, run:

which python
python --version
which pip
pip list

If you can find numpy on the list, its most likely the python version you are using is not compatible with the version of numpy installed. Try switching to a different version of Python in this case.

If numpy is not installed just pip install numpy or pip3 install numpy depending upon your version of python.

answered May 25, 2021 at 17:16

Rishabh's user avatar

RishabhRishabh

812 silver badges8 bronze badges

0

On MacOs, if you are getting this error in Pycharm and you installed Python3 and NumPy through Homebrew, the python interpreter path is probably not pointing to the Python interpreter that is installed by Homebrew. In Pycharm, go to Preferences>Project: [Project Name]>Python Interpreter, and enter /opt/homebrew/bin/python3 for the path to python interpreter.

answered Apr 27, 2022 at 3:50

Farid Rahmani's user avatar

I have a very similar question to this question, but I am still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.

I installed NumPy following this link — as suggested in the question. The installation went fine but when I execute

import numpy

I got the following error:

Import error: No module named numpy

Peter Mortensen's user avatar

asked Oct 19, 2011 at 8:54

Seb's user avatar

4

You can simply use

pip install numpy

Or for python3, use

pip3 install numpy

Daniel Patru's user avatar

answered Feb 18, 2016 at 8:51

Andrei Madalin Butnaru's user avatar

12

Installing Numpy on Windows

  1. Open Windows command prompt with administrator privileges (quick method: Press the Windows key. Type «cmd». Right-click on the
    suggested «Command Prompt» and select «Run as Administrator)
  2. Navigate to the Python installation directory’s Scripts folder using the «cd» (change directory) command. e.g. «cd C:\Program Files (x86)\PythonXX\Scripts»

This might be: C:\Users\\AppData\Local\Programs\Python\PythonXX\Scripts or C:\Program Files (x86)\PythonXX\Scripts (where XX represents the Python version number), depending on where it was installed. It may be easier to find the folder using Windows explorer, and then paste or type the address from the Explorer address bar into the command prompt.

  1. Enter the following command: «pip install numpy».

You should see something similar to the following text appear as the package is downloaded and installed.

Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)  
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3

MechtEngineer's user avatar

answered Nov 13, 2017 at 3:10

harshitha yendapally's user avatar

I think there are something wrong with the installation of numpy.
Here are my steps to solve this problem.

  1. go to this website to download correct package: http://sourceforge.net/projects/numpy/files/
  2. unzip the package
  3. go to the document
  4. use this command to install numpy: python setup.py install

legoscia's user avatar

legoscia

39.7k22 gold badges116 silver badges167 bronze badges

answered Dec 9, 2013 at 15:49

Haimei's user avatar

HaimeiHaimei

12.6k3 gold badges50 silver badges36 bronze badges

1

I also had this problem (Import Error: No module named numpy) but in my case it was a problem with my PATH variables in Mac OS X. I had made an earlier edit to my .bash_profile file that caused the paths for my Anaconda installation (and others) to not be added properly.

Just adding this comment to the list here in case other people like me come to this page with the same error message and have the same problem as I had.

Mamad Farrahi's user avatar

answered May 2, 2015 at 18:17

Bill's user avatar

BillBill

10.4k10 gold badges62 silver badges86 bronze badges

2

You can try:

py -3 -m  pip install anyPackageName

In your case use:

py -3 -m  pip install numpy

vvvvv's user avatar

vvvvv

25.7k19 gold badges49 silver badges81 bronze badges

answered Sep 14, 2019 at 5:14

Clinton Roy's user avatar

Clinton RoyClinton Roy

2,6792 gold badges10 silver badges7 bronze badges

1

You should try to install numpy using one of those:

pip install numpy
pip2 install numpy
pip3 install numpy

For some reason in my case pip2 solved the problem

answered Feb 13, 2020 at 20:16

Ateik's user avatar

AteikAteik

2,4584 gold badges39 silver badges59 bronze badges

Faced with same issue

ImportError: No module named numpy

So, in our case (we are use PIP and python 2.7) the solution was SPLIT pip install commands :

From

RUN pip install numpy scipy pandas sklearn

TO

RUN pip install numpy scipy
RUN pip install pandas sklearn

Solution found here : https://github.com/pandas-dev/pandas/issues/25193, it’s related latest update of pandas to v0.24.0

answered Feb 12, 2019 at 13:39

Nigrimmist's user avatar

NigrimmistNigrimmist

10.4k4 gold badges52 silver badges53 bronze badges

1

I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!

answered Mar 15, 2012 at 20:54

Chet's user avatar

ChetChet

21.4k10 gold badges40 silver badges58 bronze badges

I had numpy installed on the same environment both by pip and by conda, and simply removing and reinstalling either was not enough.

I had to reinstall both.

I don’t know why it suddenly happened, but the solution was

pip uninstall numpy

conda uninstall numpy

uninstalling from conda also removed torch and torchvision.

then

conda install pytorch-cpu torchvision-cpu -c pytorch

and

pip install numpy

this resolved the issue for me.

answered Dec 22, 2018 at 12:56

Gulzar's user avatar

GulzarGulzar

23.7k27 gold badges116 silver badges205 bronze badges

1

I too faced the above problem with phyton 3 while setting up python for machine learning.

I followed the below steps :-

Install python-2.7.13.msi

• set PATH=C:\Python27

• set PATH=C:\Python27\Scripts

Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Downloaded:- — numpy-1.13.1+mkl-cp27-cp27m-win32.whl

          --scipy-0.18.0-cp27-cp27m-win32.whl 

Installing numpy:
pip install numpy-1.13.1+mkl-cp27-cp27m-win32.whl

Installing scipy:
pip install scipy-0.18.0-cp27-cp27m-win32.whl

You can test the correctness using below cmds:-

>>> import numpy
>>> import scipy
>>> import sklearn
>>> numpy.version.version
'1.13.1'
>>> scipy.version.version
'0.19.1'
>>>

answered Sep 27, 2017 at 5:58

Vikram S's user avatar

Vikram SVikram S

5515 silver badges5 bronze badges

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy

answered Jul 29, 2019 at 19:05

georgeos's user avatar

georgeosgeorgeos

2,3512 gold badges24 silver badges28 bronze badges

0

I’m not sure exactly why I was getting the error, but pip3 uninstall numpy then pip3 install numpy resolved the issue for me.

answered Feb 25, 2017 at 14:12

Clay H's user avatar

Clay HClay H

6519 silver badges21 bronze badges

1

Those who are using xonsh, do xpip install numpy.

answered Feb 15, 2018 at 4:36

Necktwi's user avatar

NecktwiNecktwi

2,5137 gold badges39 silver badges63 bronze badges

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

answered Nov 1, 2017 at 4:32

Rashmi Nagpal's user avatar

import numpy as np
ImportError: No module named numpy 

I got this even though I knew numpy was installed and unsuccessfully tried all the advice above. The fix for me was to remove the as np and directly refer to modules . (python 3.4.8 on Centos)
.

import numpy
DataTwo=numpy.stack((OutputListUnixTwo))...

answered Jun 29, 2018 at 12:35

zzapper's user avatar

zzapperzzapper

4,7435 gold badges48 silver badges45 bronze badges

For me, on windows 10, I had unknowingly installed multiple python versions (One from PyCharm IDE and another from Windows store). I uninstalled the one from windows Store and just to be thorough, uninstalled numpy pip uninstall numpy and then installed it again pip install numpy. It worked in the terminal in PyCharm and also in command prompt.

answered May 15, 2020 at 4:07

Shubhzgang's user avatar

ShubhzgangShubhzgang

3222 silver badges9 bronze badges

this is the problem of the numpy’s version, please check out $CAFFE_ROOT/python/requirement.txt. Then exec: sudo apt-get install python-numpy>=x.x.x, this problem will be sloved.

answered May 11, 2016 at 15:18

zhangyi's user avatar

1

I did everything from the answers here but nothing worked. So I deleted all the previous installations of numpy using the commands below.

sudo rm -rf /usr/lib/python3/dist-packages/numpy*
sudo rm -rf /usr/lib/python3.7/dist-packages/numpy*
sudo rm -rf /usr/lib/python2.7/dist-packages/numpy*

Then just install using pip3.

sudo pip3 install numpy

Dharman's user avatar

Dharman

31.1k25 gold badges86 silver badges137 bronze badges

answered Apr 28, 2021 at 9:11

Noman's user avatar

NomanNoman

215 bronze badges

Run

conda update --all

PS recall calling python using either «python2» or «python3» (not merely «python»).

answered Oct 18, 2021 at 5:16

Itamar cohen's user avatar

solution for me — I installed numpy inside a virtual environment, but then running ipython was not inside virtual env:

(venv) ➜  which python
/Users/alon/code/google_photos_project/venv/bin/python
(venv) ➜  which ipython
/usr/bin/ipython

so I had to install ipython, and run ipython from the venv like this:

python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'

answered Aug 26, 2020 at 3:33

Alon Gouldman's user avatar

I was trying to use NumPy in Intellij but was facing the same issue so, I figured out that NumPy also comes with pandas. So, I installed pandas with IntelliJ tip and later on was able to import NumPy. Might help someone someday!

answered Aug 31, 2020 at 8:38

whatsinthename's user avatar

As stated in other answers, this error may refer to using the wrong python version. In my case, my environment is Windows 10 + Cygwin. In my Windows environment variables, the PATH points to C:\Python38 which is correct, but when I run my command like this:

./my_script.py

I got the ImportError: No module named numpy because the version used in this case is Cygwin’s own Python version even if PATH environment variable is correct.
All I needed was to run the script like this:

py my_script.py

And this way the problem was solved.

answered Sep 4, 2020 at 23:26

Metafaniel's user avatar

MetafanielMetafaniel

29.4k8 gold badges40 silver badges67 bronze badges

Try uninstalling and then reinstalling the Python extension for VSCode.

I tried many different solutions, but this «hard refresh» was the only one that worked for me.

answered Apr 14, 2021 at 10:48

Ole August Støle's user avatar

I just had the same problem as well! It turns out the problem happens when you’re installing Numpy to a version of python and trying to run the program using another python version. Probably the global version of Python your text editor opens by default is different from the one that you need for the version of numpy you are running.

So to start off, run:

which python
python --version
which pip
pip list

If you can find numpy on the list, its most likely the python version you are using is not compatible with the version of numpy installed. Try switching to a different version of Python in this case.

If numpy is not installed just pip install numpy or pip3 install numpy depending upon your version of python.

answered May 25, 2021 at 17:16

Rishabh's user avatar

RishabhRishabh

812 silver badges8 bronze badges

0

On MacOs, if you are getting this error in Pycharm and you installed Python3 and NumPy through Homebrew, the python interpreter path is probably not pointing to the Python interpreter that is installed by Homebrew. In Pycharm, go to Preferences>Project: [Project Name]>Python Interpreter, and enter /opt/homebrew/bin/python3 for the path to python interpreter.

answered Apr 27, 2022 at 3:50

Farid Rahmani's user avatar

Что означает ошибка ModuleNotFoundError: No module named

Что означает ошибка ModuleNotFoundError: No module named

Python ругается, что не может найти нужный модуль

Python ругается, что не может найти нужный модуль

Ситуация: мы решили заняться бигдатой и обработать большой массив данных на Python. Чтобы было проще, мы используем уже готовые решения и находим нужный нам код в интернете, например такой:

import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)
zeros = np.zeros((5, 4))
lin = np.linspace(1, 10, 20)

Копируем, вставляем в редактор кода и запускаем, чтобы разобраться, как что работает. Но вместо обработки данных Python выдаёт ошибку:

❌ModuleNotFoundError: No module named numpy

Странно, но этот код точно правильный: мы его взяли из блога разработчика и, по комментариям, у всех всё работает. Откуда тогда ошибка?

Что это значит: Python пытается подключить библиотеку, которую мы указали, но не может её найти у себя.

Когда встречается: когда библиотеки нет или мы неправильно написали её название.

Что делать с ошибкой ModuleNotFoundError: No module named

Самый простой способ исправить эту ошибку — установить библиотеку, которую мы хотим подключить в проект. Для установки Python-библиотек используют штатную команду pip или pip3, которая работает так: pip install <имя_библиотеки>. В нашем случае Python говорит, что он не может подключить библиотеку Numpy, поэтому пишем в командной строке такое:

pip install numpy

Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.

Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:

Что означает ошибка ModuleNotFoundError: No module named

А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.

Table of Contents
Hide
  1. Solution NameError: name ‘np’ is not defined
    1. Method 1 – Importing NumPy with Alias as np
    2. Method 2 – Importing all the functions from NumPy
    3. 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:\Personal\IJS\Code\main.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.

Avatar Of Srinivas Ramakrishna

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.

ModuleNotFoundError: no module named Python Error [Fixed]

When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python?

As the name implies, this error occurs when you’re trying to access or use a module that cannot be found. In the case of the title, the «module named Python» cannot be found.

Python here can be any module. Here’s an error when I try to import a numpys module that cannot be found:

import numpys as np

Here’s what the error looks like:

image-341

Here are a few reasons why a module may not be found:

  • you do not have the module you tried importing installed on your computer
  • you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed)…for example, spelling numpy as numpys during import
  • you use an incorrect casing for a module (which still links back to the first point)…for example, spelling numpy as NumPy during import will throw the module not found error as both modules are «not the same»
  • you are importing a module using the wrong path

How to fix the ModuleNotFoundError in Python

As I mentioned in the previous section, there are a couple of reasons a module may not be found. Here are some solutions.

1. Make sure imported modules are installed

Take for example, numpy. You use this module in your code in a file called «test.py» like this:

import numpy as np

arr = np.array([1, 2, 3])

print(arr)

If you try to run this code with python test.py and you get this error:

ModuleNotFoundError: No module named "numpy"

Then it’s most likely possible that the numpy module is not installed on your device. You can install the module like this:

python -m pip install numpy

When installed, the previous code will work correctly and you get the result printed in your terminal:

[1, 2, 3]

2. Make sure modules are spelled correctly

In some cases, you may have installed the module you need, but trying to use it still throws the ModuleNotFound error. In such cases, it could be that you spelled it incorrectly. Take, for example, this code:

import nompy as np

arr = np.array([1, 2, 3])

print(arr)

Here, you have installed numpy but running the above code throws this error:

ModuleNotFoundError: No module named "nompy"

This error comes as a result of the misspelled numpy module as nompy (with the letter o instead of u). You can fix this error by spelling the module correctly.

3. Make sure modules are in the right casing

Similar to the misspelling issue for module not found errors, it could also be that you are spelling the module correctly, but in the wrong casing. Here’s an example:

import Numpy as np

arr = np.array([1, 2, 3])

print(arr)

For this code, you have numpy installed but running the above code will throw this error:

ModuleNotFoundError: No module named 'Numpy'

Due to casing differences, numpy and Numpy are different modules. You can fix this error by spelling the module in the right casing.

4. Make sure you use the right paths

In Python, you can import modules from other files using absolute or relative paths. For this example, I’ll focus on absolute paths.

When you try to access a module from the wrong path, you will also get the module not found here. Here’s an example:

Let’s say you have a project folder called test. In it, you have two folders demoA and demoB.

demoA has an __init__.py file (to show it’s a Python package) and a test1.py module.

demoA also has an __init__.py file and a test2.py module.

Here’s the structure:

└── test
    ├── demoA
        ├── __init__.py
    │   ├── test1.py
    └── demoB
        ├── __init__.py
        ├── test2.py

Here are the contents of test1.py:

def hello():
  print("hello")

And let’s say you want to use this declared hello function in test2.py. The following code will throw a module not found error:

import demoA.test as test1

test1.hello()

This code will throw the following error:

ModuleNotFoundError: No module named 'demoA.test'

The reason for this is that we have used the wrong path to access the test1 module. The right path should be demoA.test1. When you correct that, the code works:

import demoA.test1 as test1

test1.hello()
# hello

Wrapping up

For resolving an imported module, Python checks places like the inbuilt library, installed modules, and modules in the current project. If it’s unable to resolve that module, it throws the ModuleNotFoundError.

Sometimes you do not have that module installed, so you have to install it. Sometimes it’s a misspelled module, or the naming with the wrong casing, or a wrong path. In this article, I’ve shown four possible ways of fixing this error if you experience it.

I hope you learned from it :)



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Ilife v50 pro ошибки
  • Import javax swing jframe ошибка
  • Import docx python ошибка
  • Identity ошибка please retry
  • Ilife a40 ошибки