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 thi...

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)PythonXXScripts»

This might be: C:Users\AppDataLocalProgramsPythonPythonXXScripts or C:Program Files (x86)PythonXXScripts (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.3k22 gold badges115 silver badges163 bronze badges

answered Dec 9, 2013 at 15:49

Haimei's user avatar

HaimeiHaimei

12.3k3 gold badges49 silver badges35 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.

answered May 2, 2015 at 18:17

Bill's user avatar

BillBill

9,4818 gold badges56 silver badges81 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

21.1k17 gold badges46 silver badges66 bronze badges

answered Sep 14, 2019 at 5:14

Clinton Roy's user avatar

Clinton RoyClinton Roy

2,4392 gold badges9 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,4184 gold badges37 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

9,0384 gold badges49 silver badges50 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

20.9k10 gold badges39 silver badges57 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

20.9k22 gold badges104 silver badges173 bronze badges

1

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,2682 gold badges24 silver badges27 bronze badges

0

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:Python27Scripts

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

5315 silver badges5 bronze badges

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,4137 gold badges37 silver badges61 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,6635 gold badges47 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

3132 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

29.3k21 gold badges80 silver badges131 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

28.2k7 gold badges40 silver badges65 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

1

For whom installation target is Raspberry Pi, as here they suggest:

sudo apt-get install libatlas-base-dev

could be working.

answered Jul 27, 2021 at 13:01

Shivid's user avatar

ShividShivid

1,2131 gold badge21 silver badges36 bronze badges

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)PythonXXScripts»

This might be: C:Users\AppDataLocalProgramsPythonPythonXXScripts or C:Program Files (x86)PythonXXScripts (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.3k22 gold badges115 silver badges163 bronze badges

answered Dec 9, 2013 at 15:49

Haimei's user avatar

HaimeiHaimei

12.3k3 gold badges49 silver badges35 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.

answered May 2, 2015 at 18:17

Bill's user avatar

BillBill

9,4818 gold badges56 silver badges81 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

21.1k17 gold badges46 silver badges66 bronze badges

answered Sep 14, 2019 at 5:14

Clinton Roy's user avatar

Clinton RoyClinton Roy

2,4392 gold badges9 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,4184 gold badges37 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

9,0384 gold badges49 silver badges50 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

20.9k10 gold badges39 silver badges57 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

20.9k22 gold badges104 silver badges173 bronze badges

1

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,2682 gold badges24 silver badges27 bronze badges

0

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:Python27Scripts

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

5315 silver badges5 bronze badges

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,4137 gold badges37 silver badges61 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,6635 gold badges47 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

3132 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

29.3k21 gold badges80 silver badges131 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

28.2k7 gold badges40 silver badges65 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

1

For whom installation target is Raspberry Pi, as here they suggest:

sudo apt-get install libatlas-base-dev

could be working.

answered Jul 27, 2021 at 13:01

Shivid's user avatar

ShividShivid

1,2131 gold badge21 silver badges36 bronze badges

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

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

Вёрстка:

Кирилл Климентьев

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

A common error you may encounter when using Python is modulenotfounderror: no module named ‘numpy’. This error occurs when Python cannot detect the NumPy library in your current environment. This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.

Table of contents

  • ModuleNotFoundError: no module named ‘numpy’
    • What is ModuleNotFoundError?
    • What is Numpy?
    • How to Install Numpy on Windows Operating System
    • How to Install Numpy on Mac Operating System
    • How to Install Numpy on Linux Operating Systems
      • Installing pip for Ubuntu, Debian, and Linux Mint
      • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
      • Installing pip for CentOS 6 and 7, and older versions of Red Hat
      • Installing pip for Arch Linux and Manjaro
      • Installing pip for OpenSUSE
    • Check NumPy Version
    • Installing Numpy Using Anaconda
  • Summary

ModuleNotFoundError: no module named ‘numpy’

What is ModuleNotFoundError?

The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:

The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:

import ree
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
1 import ree

ModuleNotFoundError: No module named 'ree'

To solve this error, ensure the module name is correct. Let’s look at the revised code:

import re

print(re.__version__)
2.2.1

You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:

mkdir example_package

cd example_package

mkdir folder_1

cd folder_1

vi module.py

Note that we are using Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:

import re

def print_re_version():

    print(re.__version__)

Close the module.py, then complete the following commands from your terminal:

cd ../

vi script.py

Inside script.py, we will try to import the module we created.

import module

if __name__ == '__main__':

    mod.print_re_version()

Let’s run python script.py from the terminal to see what happens:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import module
ModuleNotFoundError: No module named 'module'

To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:

import folder_1.module as mod

if __name__ == '__main__':

    mod.print_re_version()

When we run python script.py, we will get the following result:

2.2.1

Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.

What is Numpy?

NumPy is the fundamental Python library for scientific computing. The library provides a multidimensional array object, the ndarray and routines and operations for manipulating multidimensional arrays. NumPy does not come installed automatically with Python. The easiest way to install NumPy is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.

How to Install Numpy on Windows Operating System

To install NumPy using pip on Windows, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically installed on Windows for Python versions 2.7.9+ and 3.4+.

You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

python get-pip.py

You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

pip --version

To install numpy with pip, run the following command from the command prompt.

pip3 install numpy

How to Install Numpy on Mac Operating System

Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter.

To get pip, first ensure you have installed Python3:

python3 --version
Python 3.8.8

Download pip by running the following curl command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

The curl command allows you to specify a direct download link, and using the -o option sets the name of the downloaded file.

Install pip by running:

python3 get-pip.py

From the terminal, use the pip3 command to install numpy:

pip3 install numpy

How to Install Numpy on Linux Operating Systems

All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip and numpy. Open a terminal and use the commands relevant to your Linux distribution to install pip.

Installing pip for Ubuntu, Debian, and Linux Mint

sudo apt install python-pip3

Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

sudo dnf install python-pip3

Installing pip for CentOS 6 and 7, and older versions of Red Hat

sudo yum install epel-release

sudo yum install python-pip3

Installing pip for Arch Linux and Manjaro

sudo pacman -S python-pip

Installing pip for OpenSUSE

sudo zypper python3-pip

Once you have installed pip, you can install numpy using:

pip3 install numpy

Check NumPy Version

Once you have successfully installed NumPy, you can use two methods to check the version of NumPy. First, you can use pip from your terminal:

pip show numpy
Name: numpy
Version: 1.18.5
Summary: NumPy is the fundamental package for array computing with Python.
Home-page: https://www.numpy.org
Author: Travis E. Oliphant et al.
Author-email: None
License: BSD
Location: /Users/Yusufu.Shehu/opt/anaconda3/lib/python3.8/site-packages
Requires: 
Required-by: tifffile, tensorflow, tensorboard, tables, statsmodels, seaborn, scipy, scikit-learn, scikit-image, PyWavelets, pyerfa, patsy, pandas, opt-einsum, numexpr, numba, mlxtend, mkl-random, mkl-fft, matplotlib, Keras, Keras-Preprocessing, Keras-Applications, imbalanced-learn, imageio, h5py, gym, gensim, Bottleneck, bokeh, bkcharts, astropy

Second, within your python program, you can import numpy and then reference the __version__ attribute:

import numpy as np

print(np.__version__)
1.18.5

Installing Numpy Using Anaconda

Anaconda is a distribution of Python and R for scientific computing and data science. Anaconda comes with numpy and other relevant Python libraries for data science and machine learning. You can install Anaconda by going to the installation instructions.

You can install numpy in your conda environment using the following command from your terminal or command prompt:

conda install -c anaconda numpy

Summary

Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system, which comes with numpy.

For further reading on installing data science and machine learning libraries, you can go to the articles:

  • OpenCV: How to Solve Python ModuleNotFoundError: no module named ‘cv2’
  • Requests: How to Solve Python ModuleNotFoundError: no module named ‘requests’
  • Pandas: How to Solve Python ModuleNotFoundError: no module named ‘pandas’
  • Matplotlib: How to Solve Python ModuleNotFoundError: no module named ‘matplotlib’
  • Flask: How to Solve Python ModuleNotFoundError: no module named ‘flask’

For further reading on using numpy arrays go to the article: How-to Guide for Python NumPy Where Function.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Summary: The most common cause of ModuleNotFoundError is a faulty installation of the module or importing a module incorrectly. For a successful installation of the module, use pip3 install numpy.

Table of Contents

  • ◈ Overview
    • ➥ Reasons of Import Error: No module Named ‘xyz’
  • ◈ Solution
    • ❋ Method 1: Fixing Faulty Installation
    • ❋ Method 2: Fixing Missing Path
  • ◈ Scenario 2: ModuleNotFoundError In Case Of User-Defined Modules
  • Conclusion

◈ Overview

If you are someone like me who works with lots and lots of data, then Import Error: No module named 'xyz' is probably one of the most common errors that you have come across. In this article, I will discuss the causes and solutions to this error in Python.

Example: Suppose that you are trying to import the Numpy library and print an array. However you get an ImportError: ModuleNotFoundError: No module named 'numpy'.

import numpy as np

arr = np.array((1, 2, 3, 4, 5))

print(arr)

Output:

➥ Reasons of Import Error: No module Named ‘xyz’

Two major reasons that lead to the occurrence of this error:

  • You have not installed the module correctly, i.e., you are using an older version of the module, which is not compatible with the version of Python you are using.
  •  The Python-version/environment where you installed the package is not the same.
    • Note: This usually happens when you have two versions of Python (Python 2.x and Python 3.x simultaneously) installed on your system.

◈ Solution

Let us dive into the probable solutions to our problem.

❋ Method 1: Fixing Faulty Installation

If you are on Python version 3, then you must install the latest version of the package. In our case, we must install the latest version of Numpy. Before we dive into the commands to install the latest version of Numpy, let us look at the following visual, which explains what happens when you try to install an older version of Numpy on Python 3.

Thus, it is clear from the above example that even though you installed Numpy, the ModuleNotFoundError was not resolved. The reason is you installed an older version of Numpy ,which is incompatible with Python 3.

Note:

  • The command to install a particular version of Numpy is:- pip install numpy==x.y.z
    • Here x.y.z re[resents the version of Numpy you want to install, for example:- numpy==1.8.2

To resolve this issue, you can use the following command in your terminal to ensure that the latest version of Numpy is installed:

pip3 install numpy

Let’s have a look at the following graphic to visualize the solution.

❋ Method 2: Fixing Missing Path

Sometimes, even the above procedure does not work. Whenever you import a module, python searches the module in specific directories.

To get hold of all the directories that Python will search, you can use piece of code:

import sys

for path in sys.path:

    print(path)

Output:

Disclaimer: The paths shown in this output will vary from user to user.

D:PycharmProjectspythonProject1
D:PycharmProjectspythonProject1
C:Program Files (x86)Python38-32python38.zip
C:Program Files (x86)Python38-32DLLs
C:Program Files (x86)Python38-32lib
C:Program Files (x86)Python38-32
C:UsersDELLAppDataRoamingPythonPython38site-packages
C:Program Files (x86)Python38-32libsite-packages

You should make sure that the NumPy module resides in any of these directories. Once a module has been imported, you can find its location with the help of the module’s __file__ attribute:

import numpy as np

print(np.__file__)

Output:

Disclaimer: The paths shown in this output will vary from user to user.

C:UsersDELLAppDataRoamingPythonPython38site-packagesnumpy__init__.py

If the NumPy module is not found in any of the listed directories, then you have to append it to the python search path using the following statements:

import sys

sys.path.append(«Path to NumPy Module»)

import numpy as np

You also have other options to ensure that your module is found. These are:

  • Put module.py inside the directory containing the input script.
  • Modify the environment variable: PYTHONPATH and ensure that it contains the directory where module.py is located before you start the interpreter.
    • You can also opt to put mod.py in one of the directories already present in the PYTHONPATH environment variable.

In case you are struggling with this error despite following all the above methods, and you are using Jupyter Notebook, then you might want to have a look at this article.

◈ Scenario 2: ModuleNotFoundError In Case Of User-Defined Modules

Previously we found out how to resolve the ModuleNotFoundError when we are dealing with in-built modules/packages. If you are working with user-defined modules, you may still encounter this problem.

Example: Consider that you have created a user- defined module ex. This module is within a directory named UserDefinedModule.

def foo():

    print(«This is a User Defined Module!»)

Now you want to import this module into your program as shown below:

import ex

print(‘Python!’)

ex.foo()

Output:

Explanation:

The module ex is not a part of the current working directory. Therefore, Python is unable to import the required module successfully.

Solutions:

  • The first solution is to make sure that the module being imported and the program that imports the module are in the same directory.
  • The second way of avoiding this error is to import the module from its relative path as shown in the illustration given below.

Explanation:

Since the ex module is contained within the UserDefinedModule directory, so you must import it from this folder itself using the import statement: from UserDefinedModule import ex

Conclusion

In this article, you learned how to avoid the ModuleNotFoundError in Python.

  • While working with an external module, make sure you have installed it properly.
  • While working with a user-defined module, you must use your import statements properly and ensure that the modules are imported from their relative paths.

Please subscribe and stay tuned for exciting articles. Happy learning! 📚

In this Python NumPy tutorial, we will learn how to fix the python NumPy not found error. Also, we will cover these topics.

  • Python Numpy Not Found
  • Ubuntu Python Numpy Not Found
  • Anaconda Python Numpy Not Found
  • Vscode Python Numpy Not found
  • Python Numpy dll Not Found
  • Python Numpy Include Path-Not Found
  • Python Import Numpy Not Working
  • Python Numpy Transpose Not Working

Sometimes, the error looks like below:

No module named "numpy"
Python Numpy Not Found

In this section, we will learn to fix the error Python NumPy not found or no module named ‘numpy’.

python numpy not found
Python Numpy Not found
  • Python numpy not found or no module named ‘numpy’ error appears when the module is not installed in the current working environment.
  • Install the module using pip or conda to fix this issue. but make sure that you have installed it in current working environment.
# installation using pip
pip install numpy

# installation using conda
conda install numpy
  • You can install the numpy module even while working on jupyter notebook. Use the below syntax on the jupyter notebook and run it before importing numpy module.

!pip install numpy

# or

!conda install numpy

In the below implementation, when we tried to access the numpy module import numpy it threw an error No module named ‘numpy’. Then we have installed the module using pip now it didn’t thew any error.

Python Numpy Not Found Solution
Python Numpy Not Found

Read Check if NumPy Array is Empty in Python

Ubuntu Python Numpy Not Found

In this section, we will learn how to fix the error python numpy not found in the Ubuntu operating system.

  • Ubuntu is a linux based operating system that has different filesystem then windows operating system.
  • But using pip or conda we can bridge this difference and can use numpy independently on any operating system ( Linux, Windows, macOS).
  • Using apt package manager in Ubuntu machine we can install numpy. Here is the command to do so.
sudo apt install python3-numpy
  • Please note that this command will install numpy on the system that can be accessed bydefault. but it won’t work if you have created a new envirnoment. Either deactivate the environment or install numpy on that environment to access numpy.
  • In the below demonstration, we have installed numpy on the system. Then we have created a virtual environment to check if it is working over there as well. It do not work on the new virtual environment.
Ubuntu Python Numpy Not Found
Ubuntu Python Numpy Not Found

Read Python NumPy zeros

Anaconda Python Numpy Not Found

In this section, we will learn how to fix the python NumPy not found error in anaconda.

  • Anaconda is a package management and deployement software dedicated specially for data science modules.
  • The data science packages offered by anaconda are compatible on Linux, Macintosh (macOS) and windows operating system.
  • Basic packages like jupyter notebbok, pandas, numpy, matplotlib, etc are already available when anaconda installed on the system.
  • If you don’t want these pre-installed packages then either you can remove them or go for miniconda3 which is lighter version of anaconda and it has no packages pre-installed.
  • In our example, we have demonstrated how to fix anaconda python numpy not found error or No module named ‘numpy’. Incase you already have numpy installed and is not working then reinstall it.
  • Here is the code to uninstall the numpy module from anaconda package manager.
conda remove numpy
  • Here is the code to install numpy module in anaconda package manager.
conda install numpy

Here is the demonstration of uninstallation and installation of numpy on anaconda in python.

Anaconda Python Numpy Not Found Solution
Anaconda Python Numpy Not Found Solution

Read Python NumPy arange

Vscode Python Numpy Not found

In this section, we will learn how to fix the Python NumPy not found error in vscode.

  • Python Numpy not found or no module found ‘numpy’ error in vscode can be fixed by install the numpy module extension in vscode.
  • We can also use pip or conda package managers to fix this issue. In case you have installed the module still same error is appearing that means have to activate the dedicated environment.
  • Use the below code to install python numpy on vscode. In case you have already installed it but unable to access it then skip to next point.
pip install numpy
  • In vscode, most of the time we forget to keep check on the environment we are working on. There are multiple environments present on the vscode like virtual environment (self created), conda base environment, conda other environments (if any), global environment, etc.
  • You may have installed the numpy module on the global module but now you are working on vritual environment created by you.
  • Apart from this, keep a check of python interpreter installed in your system. Make sure you have selected the same interpreter that you have used while installing numpy.
  • There were the major reasons for Vscode Python Numpy Not found.

Read Python Numpy Factorial

Python Numpy dll Not Found

In this section, we will learn how to fix the python numpy dll not found error.

ImportError: DLL load failed while importing path: The specified module could not be found.

or

ImportError: DLL load failed: The specified module could not be found.
  • DLL is dynamic link library which is used by more than one program on the windows computer.
  • Python numpy dll not found error can be resolved by reinstalling the numpy on the computer/environment.
  • In case issue is still not resolved then download Visual C++ Redistributable for Visual Studio 2015.
  • Once you have installed it restart your computer and try to run the program again.
  • In case issue still persist, please leave the exact error message in the comment section of this blog.

Read Python NumPy Delete

Python Numpy Include Path-Not Found

In this section, we will learn how to fix python numpy include path-not-found error. This section will also cover Python Checking for Numpy – Not Found.

  • All the modules installed must go inside the site-packages folder in all the operating systems for the smooth running of that module.
  • In case while installing numpy manually you have not placed the module inside the site-package folder in windows machine and dist-packages folder in linux and macOS then python numpy include path not found error may occur.
  • Also, you may have multiple versions of python installed in your system and there are chances that wrong interpreter is selected while executing the program. This way also you won’t be able to access the numpy module.
  • Below we have shown the ways to see the current path where numpy module is installed.
# using pip
python -m pip show numpy
Python Numpy Installed Path-in-Linux
Python Numpy Installed Path-in-Linux
Python NumPy Installed Path-in-Windows
Python Numpy Installed Path-in-Windows
# using anaconda
conda list numpy
Python Numpy Installed Path-in-Linux using anaconda
Python Numpy Installed Path-in-Linux using anaconda

Read Python NumPy Sum

Python Import Numpy Not Working

In this section, we will learn how to fix python import numpy not working error.

  • Python import numpy is not working that means eithers the module is not installed or the module is corrupted.
  • To fix the corrupted module, uninstall it first then reinstall it.
# pip users follow these steps

pip uninstall numpy
pip install numpy

# conda users follow these steps
conda remove numpy
conda install numpy
  • If you are getting an error ” No module found ‘numpy’ then install the module using pip or conda package manager.
pip install numpy

or 

conda install numpy
  • In case you are not using package mangers and want to install numpy on bare metal than windows users can download numpy from this website and linux or macOS users can follow the below command.
# Linux Debian (ubuntu)
sudo apt install numpy

# Linux RHEL
yum install numpy

# macOS 
brew install numpy

Read Python NumPy square with examples

Python Numpy Transpose Not Working

In this section, we will learn how to fix the python numpy transpose not working error.

  • Transpose refers to changing position of values in the array in python numpy.
  • Using numpy.transpose() method in python numpy we can perform transpose an array.
  • Python numpy transpose method reverses the shape of an array. Suppose the shape of an array is (5, 2,3) so after applyting transpose function it will become (3, 2, 5).
  • Incase the array is of 1D then no effect of transpose method will be displayed.
  • In our example, we have displayed both 1D and multiple dimensional array.

Source Code:

In this source code, we have performed python numpy transpose using single and multiple dimensional arrays.

import numpy as np

# one dimensional array
arry = np.arange(10).reshape(10)
arry.transpose()

# multiple dimensional array
arr = np.arange(30).reshape(5, 3, 2)
arr.transpose()

Output:

In this output, we have demonstrated transpose on single-dimensional array. No change is observed as the transpose method reverses the shape of the numpy array. Since this has a single shape so it can’t be reversed.

Python Numpy Transpose Not Working with one dimensional array
Python Numpy Transpose with one-dimensional array

In this output, a multiple dimensional array got created, and when we have applied the transpose method on this array the shape is reversed from (5, 3, 2) to (2, 3, 5).

Python Numpy Transpose Not Working with multiple dimensional array
Python Numpy Transpose with multiple dimensional array

Related Python NumPy tutorials:

  • Python Absolute Value
  • Python NumPy Divide
  • Python NumPy Add Tutorial
  • Python NumPy Count – Useful Guide
  • Python NumPy to list with examples
  • Python NumPy read CSV
  • Python NumPy log
  • Python NumPy where with examples

In this Python tutorial, we have learned how to fix the python numpy not found error. Also, we have covered these topics.

  • Python Numpy Not Found
  • Ubuntu Python Numpy Not Found
  • Anaconda Python Numpy Not Found
  • Vscode Python Numpy Not found
  • Python Numpy dll Not Found
  • Python Numpy Include Path-Not Found
  • Python Import Numpy Not Working
  • Python Numpy Transpose Not Working

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Note

Since this information may be updated regularly, please ensure you are
viewing the most up-to-date version.

ImportError#

In certain cases a failed installation or setup issue can cause you to
see the following error message:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy c-extensions failed. This error can happen for
different reasons, often due to issues with your setup.

The error also has additional information to help you troubleshoot:

  • Your Python version

  • Your NumPy version

Please check both of these carefully to see if they are what you expect.
You may need to check your PATH or PYTHONPATH environment variables
(see Check Environment Variables below).

The following sections list commonly reported issues depending on your setup.
If you have an issue/solution that you think should appear please open a
NumPy issue so that it will be added.

There are a few commonly reported issues depending on your system/setup.
If none of the following tips help you, please be sure to note the following:

  • how you installed Python

  • how you installed NumPy

  • your operating system

  • whether or not you have multiple versions of Python installed

  • if you built from source, your compiler versions and ideally a build log

when investigating further and asking for support.

Using Python from conda (Anaconda)#

Please make sure that you have activated your conda environment.
See also the conda user-guide.
If you use an external editor/development environment it will have to be set
up correctly. See below for solutions for some common setups.

Using PyCharm with Anaconda/conda Python#

There are fairly common issues when using PyCharm together with Anaconda,
please see the PyCharm support

Using VSCode with Anaconda/conda Python (or environments)#

A commonly reported issue is related to the environment activation within
VSCode. Please see the VSCode support
for information on how to correctly set up VSCode with virtual environments
or conda.

Using Eclipse/PyDev with Anaconda/conda Python (or environments)#

Please see the
Anaconda Documentation
on how to properly configure Eclipse/PyDev to use Anaconda Python with specific
conda environments.

Raspberry Pi#

There are sometimes issues reported on Raspberry Pi setups when installing
using pip3 install (or pip install). These will typically mention:

libf77blas.so.3: cannot open shared object file: No such file or directory

The solution will be to either:

sudo apt-get install libatlas-base-dev

to install the missing libraries expected by the self-compiled NumPy
(ATLAS is a possible provider of linear algebra).

Alternatively use the NumPy provided by Raspbian. In which case run:

pip3 uninstall numpy  # remove previously installed version
apt install python3-numpy

Debug build on Windows#

Rather than building your project in DEBUG mode on windows, try
building in RELEASE mode with debug symbols and no optimization.
Full DEBUG mode on windows changes the names of the DLLs python
expects to find, so if you wish to truly work in DEBUG mode you will
need to recompile the entire stack of python modules you work with
including NumPy

All Setups#

Occasionally there may be simple issues with old or bad installations
of NumPy. In this case you may just try to uninstall and reinstall NumPy.
Make sure that NumPy is not found after uninstalling.

Development Setup#

If you are using a development setup, make sure to run git clean -xdf
to delete all files not under version control (be careful not to lose
any modifications you made, e.g. site.cfg).
In many cases files from old builds may lead to incorrect builds.

Check Environment Variables#

In general how to set and check your environment variables depends on
your system. If you can open a correct python shell, you can also run the
following in python:

import os
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
print("PATH:", os.environ.get('PATH'))

This may mainly help you if you are not running the python and/or NumPy
version you are expecting to run.

C-API incompatibility#

If you see an error like:

RuntimeError: module compiled against API version v1 but this version of numpy is v2

You may have:

  • A bad extension “wheel” (binary install) that should use
    oldest-support-numpy (
    with manual constraints if necessary) to build their binary packages.

  • An environment issue messing with package versions.

  • Incompatible package versions somehow enforced manually.

  • An extension module compiled locally against a very recent version
    followed by a NumPy downgrade.

  • A compiled extension copied to a different computer with an
    older NumPy version.

The best thing to do if you see this error is to contact
the maintainers of the package that is causing problem
so that they can solve the problem properly.

However, while you wait for a solution, a work around
that usually works is to upgrade the NumPy version:

pip install numpy --upgrade

Segfaults or crashes#

NumPy tries to use advanced CPU features (SIMD) to speed up operations. If you
are getting an “illegal instruction” error or a segfault, one cause could be
that the environment claims it can support one or more of these features but
actually cannot. This can happen inside a docker image or a VM (qemu, VMWare,
…)

You can use the output of np.show_runtime() to show which SIMD features are
detected. For instance:

>>> np.show_runtime()
WARNING: `threadpoolctl` not found in system! Install it by `pip install 
threadpoolctl`. Once installed, try `np.show_runtime` again for more detailed
build information
[{'simd_extensions': {'baseline': ['SSE', 'SSE2', 'SSE3'],
                      'found': ['SSSE3',
                                'SSE41',
                                'POPCNT',
                                'SSE42',
                                'AVX',
                                'F16C',
                                'FMA3',
                                'AVX2'],
                      'not_found': ['AVX512F',
                                    'AVX512CD',
                                    'AVX512_KNL',
                                    'AVX512_KNM',
                                    'AVX512_SKX',
                                    'AVX512_CLX',
                                    'AVX512_CNL',
                                    'AVX512_ICL']}}]

In this case, it shows AVX2 and FMA3 under the found section, so you can
try disabling them by setting NPY_DISABLE_CPU_FEATURES="AVX2,FMA3" in your
environment before running python (for cmd.exe on windows):

>SET NPY_DISABLE_CPU_FEATURES="AVX2,FMA3"
>python <myprogram.py>

By installing threadpoolctl np.show_runtime() will show additional information:

...
{'architecture': 'Zen',
  'filepath': '/tmp/venv3/lib/python3.9/site-packages/numpy.libs/libopenblas64_p-r0-15028c96.3.21.so',
  'internal_api': 'openblas',
  'num_threads': 24,
  'prefix': 'libopenblas',
  'threading_layer': 'pthreads',
  'user_api': 'blas',
  'version': '0.3.21'}]

If you use the wheel from PyPI, it contains code from the OpenBLAS project to
speed up matrix operations. This code too can try to use SIMD instructions. It
has a different mechanism for choosing which to use, based on a CPU
architecture, You can override this architecture by setting
OPENBLAS_CORETYPE: a minimal value for x86_64 is
OPENBLAS_CORETYPE=Haswell. This too needs to be set before running your
python (this time for posix):

$ OPENBLAS_CORETYPE=Haswell python <myprogram.py>

Понравилась статья? Поделить с друзьями:
  • Imax b6 ошибка input vol err
  • Imax b6 ошибка cell error voltage invalid
  • Imax b6 ошибка balance connect error
  • Imax b6 mini balance connect error как исправить
  • Imaplib imap4 error command search illegal in state auth only allowed in states selected