Pycharm ошибка no module named

I have written a module (a file my_mod.py file residing in the folder my_module).
Currently, I am working in the file cool_script.py that resides in the folder cur_proj. I have opened the folder in PyCharm using File — open (and I assume, hence, it is a PyCharm project).

In ProjectView (CMD-7), I can see my project cur_proj (in red) and under «External Libraries» I do see my_module. In cool_script.py, I can write

from my_module import my_mod as mm

and PyCharm even makes suggestion for my_mod. So far so good.

However, when I try to run cool_script.py, PyCharm tells me
«No module named my_module»

This seems strange to me, because

A) in the terminal (OS 10.10.2), in python, I can import the module no problem — there is a corresponding entry in the PYTHONPATH in .bashrc

B) in PyCharm — Settings — Project cur_proj — Project Interpreter — CogWheel next to python interpreter — more — show paths for selected interpreter icon, the paths from PYTHONPATH do appear (as I think they should)

Hence, why do I get the error when I try to run cool_script.py? — What am I missing?

Notes:

  • I am not declaring a different / special python version at the top of cool_script.py
  • I made sure that the path to my_module is correct
  • I put __init__.py files (empty files) both in my_module and in cur_proj
  • I am not using virtualenv

Addendum 2015-Feb-25

When I go in PyCharm to Run — Edit Configurations, for my current project, there are two options that are selected with a check mark: «Add content roots to PYTHONPATH» and «Add source roots to PYTHONPATH«. When I have both unchecked, I can load my module.

So it works now — but why?

Further questions emerged:

  • What are «content roots» and what are «source roots»? And why does adding something to the PYTHONPATH make it somehow break?
  • should I uncheck both of those options all the time (so also in the defaults, not only the project specific configurations (left panel of the Run/Debug Configurations dialog)?

I have written a module (a file my_mod.py file residing in the folder my_module).
Currently, I am working in the file cool_script.py that resides in the folder cur_proj. I have opened the folder in PyCharm using File — open (and I assume, hence, it is a PyCharm project).

In ProjectView (CMD-7), I can see my project cur_proj (in red) and under «External Libraries» I do see my_module. In cool_script.py, I can write

from my_module import my_mod as mm

and PyCharm even makes suggestion for my_mod. So far so good.

However, when I try to run cool_script.py, PyCharm tells me
«No module named my_module»

This seems strange to me, because

A) in the terminal (OS 10.10.2), in python, I can import the module no problem — there is a corresponding entry in the PYTHONPATH in .bashrc

B) in PyCharm — Settings — Project cur_proj — Project Interpreter — CogWheel next to python interpreter — more — show paths for selected interpreter icon, the paths from PYTHONPATH do appear (as I think they should)

Hence, why do I get the error when I try to run cool_script.py? — What am I missing?

Notes:

  • I am not declaring a different / special python version at the top of cool_script.py
  • I made sure that the path to my_module is correct
  • I put __init__.py files (empty files) both in my_module and in cur_proj
  • I am not using virtualenv

Addendum 2015-Feb-25

When I go in PyCharm to Run — Edit Configurations, for my current project, there are two options that are selected with a check mark: «Add content roots to PYTHONPATH» and «Add source roots to PYTHONPATH«. When I have both unchecked, I can load my module.

So it works now — but why?

Further questions emerged:

  • What are «content roots» and what are «source roots»? And why does adding something to the PYTHONPATH make it somehow break?
  • should I uncheck both of those options all the time (so also in the defaults, not only the project specific configurations (left panel of the Run/Debug Configurations dialog)?

В Python может быть несколько причин возникновения ошибки ModuleNotFoundError: No module named ...:

  • Модуль Python не установлен.
  • Есть конфликт в названиях пакета и модуля.
  • Есть конфликт зависимости модулей Python.

Рассмотрим варианты их решения.

Модуль не установлен

В первую очередь нужно проверить, установлен ли модуль. Для использования модуля в программе его нужно установить. Например, если попробовать использовать numpy без установки с помощью pip install будет следующая ошибка:

Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'numpy'

Для установки нужного модуля используйте следующую команду:

pip install numpy
# или
pip3 install numpy

Или вот эту если используете Anaconda:

conda install numpy

Учтите, что может быть несколько экземпляров Python (или виртуальных сред) в системе. Модуль нужно устанавливать в определенный экземпляр.

Конфликт имен библиотеки и модуля

Еще одна причина ошибки No module named — конфликт в названиях пакета и модуля. Предположим, есть следующая структура проекта Python:

demo-project
 └───utils
         __init__.py
         string_utils.py
         utils.py

Если использовать следующую инструкцию импорта файла utils.py, то Python вернет ошибку ModuleNotFoundError.


>>> import utils.string_utils
Traceback (most recent call last):
File "C:\demo-project\utils\utils.py", line 1, in
import utils.string_utils
ModuleNotFoundError: No module named 'utils.string_utils';
'utils' is not a package

В сообщении об ошибке сказано, что «utils is not a package». utils — это имя пакета, но это также и имя модуля. Это приводит к конфликту, когда имя модуля перекрывает имя пакета/библиотеки. Для его разрешения нужно переименовать файл utils.py.

Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.

Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester.

Traceback (most recent call last):
   File "C:\demo-project\venv\
Lib\site-packages\
         scipy\_lib\_numpy_compat.py", line 10, in
     from numpy.testing.nosetester import import_nose
 ModuleNotFoundError: No module named 'numpy.testing.nosetester'

Ошибка ModuleNotFoundError возникает из-за того, что модуль numpy.testing.nosetester удален из библиотеки в версии 1.18. Для решения этой проблемы нужно обновить numpy и scipy до последних версий.

pip install numpy --upgrade
pip install scipy --upgrade 
  • The Problem

    • The Error
    • Process of Debugging

      • Additional Thoughts
  • Thoughts on the problem
  • Links
  • Outro

The Problem

Today I stumbled upon to a not a very straightforward issue while using IntelliJ IDEA via Python Plugin, and PyCharm. In other words IntelliJ IDEA and PyCharm not recognizing installed packages inside virtual environment.

When running the script via Run button, it blows up with an error but when running the script from the command line it runs with no errors, as it supposed to.

The Error (via Run button)

$ python wierd_error.py

Traceback (most recent call last):
  File "C:\Users\path_to_file", line 943, in <module>
    import bcrypt
ModuleNotFoundError: No module named 'bcrypt'

Enter fullscreen mode

Exit fullscreen mode

  1. Python script is executing.
  2. When trying to import a package blows up with an error.

The error is clearly says:

Hey man, there’s no bcrypt module, just go and install it.

BUT (DUDE, THE MODULE IS RIGHT THERE! COME ON!) it was already installed to the virtual environment, and I’m not really sure if I did something wrong, or the program didn’t do what I expected. But at that moment I wanted to break the table in half.

Before running the script I’ve created a env folder for a project to isolate it from globally installed packages.

python -m venv env

Enter fullscreen mode

Exit fullscreen mode

Then I activate it:

$ source env/Scripts/activate

(env)

Enter fullscreen mode

Exit fullscreen mode

After that, I installed a few packages via pip install. They were installed to env folder as they should, and I confirmed it via pip list command to print out all install packages in the virtualenv.

$ pip list

Package    Version
---------- -------
bcrypt     3.2.0    <-- It's there!
pip        21.1.1
setuptools 56.0.0

Enter fullscreen mode

Exit fullscreen mode

So why on Earth does the script blows up with an error while using Run button but runs smoothly from the command line both inside IntelliJ IDEA and PyCharm?

Process of debugging

Idea 1. Tinker everything inside Project Structure settings

The following examples will be from IntelliJ IDEA but almost the same thing happening in the PyCharm.

Image description

I was trying to change project interpreter SDK/Setting, create module (inside project structure settings) for absolute no reason just to test if it helps. There’s not much I could say about this idea, but this process goes in circle for a few hours in and Googling related things at the same time.

Idea 2. Test in other IDE

After trying the same thing for a few hours I tried to test if the same behavior will be in other IDE’s such as PyCharm and VSCode. And the answer is «Yes», same behavior, in terminal runs, via Run button explodes with an error.

At that point I understand that something happening inside IDE since running from a command line everything runs as it should, so I focused on figuring out what causes error inside IDE.

Idea 3. Google «pycharm not recognizing installed packages»

At this point I was trying to formulate a problem in order to google it. The first Google results was exactly what I was looking for PyCharm doesn’t recognise installed module.

This is the answer that helped to solve the problem which said:

Pycharm is unable to recognize installed local modules, since python interpreter selected is wrong. It should be the one, where your pip packages are installed i.e. virtual environment.

The person who answer the question had the similar problem I had:

I had installed packages via pip in Windows. In Pycharm, they were neither detected nor any other Python interpreter was being shown (only python 3.6 is installed on my system).

Step 4. Change Project SDK to python.exe from virtual environment

In order to make it work I first found where python.exe inside virtual environment folder is located, and copied the full path.

Then, go to Project Structure settings (CTRL+ALT+SHIFT+S) -> SDK's -> Add new SDK -> Add Python SDK -> System interpreter -> changed existing path to the one I just copied. Done!

Path changed from this:

Image description

To this:

Image description

One thing left. We also need to change Python interpreter path inside Run Configuration to the one that was just created inside System Interpreter under Project Structure:

Image description

Changing Python interpreter path from the default one:

Image description

Additional Thoughts

I’m not creating another virtual environment (venv) that PyCharm provides because I already create it from the command line beforehand, that’s why I change path inside System Interpreter.

It can be also achieved by creating new Virtual Environment instead of creating it from command line (basically the same process as described above):

  • Set Base Interpreter to whatever Python version is running.

  • Make sure that Project SDK (Project Structure window) is set to the one from Virtual Environment (Python 3.9 (some words)).

  • Open Run Configuration -> Python Interpreter -> Use specific interpreter path is set to python.exe path from the venv folder (e.g. newly created virtual environment).

Note: When using such method, Bash commands not found for unknown for me reason.

$ which python

bash: which: command not found
()  <- tells that you're currently in virtualenv

Enter fullscreen mode

Exit fullscreen mode

But when creating env manually (python -m venv env), Bash commands are working.


Thoughts on the problem

I thought that IntelliJ IDEA, PyCharm handles such things under the hood so end user doesn’t have to think about it, just create an env, activate it via $ source env/Scripts/activate and it works.

I should skip tinkering step right away after few minutes of trying to formulate the problem correctly and googling it instead of torture myself for over an hour.

In the end, I’m happy that I’ve stumbled upon such problem because with new problems it will be much easier to understand what steps to do based on the previous experience.


Links

  • StackOverflow question
  • StackOverflow answer
  • Googling the problem

Outro

If you have anything to share, any questions, suggestions, feel free to drop a comment in the comment section or reach out via Twitter at @dimitryzub.

Yours,
Dimitry

ModuleNotFoundError — No Module Named ‘Pandas’

The ModuleNotFoundError — No Module Named ‘Pandas’ error occurs because the Python interpreter can’t locate your installation of the Pandas library. The easiest solution is to make sure Pandas is installed, which you can do with the following shell commands, depending on your Python installation (either Pip or Anaconda):

  • Pip: Run pip install pandas
  • Anaconda: Run conda install pandas

However, there are more reasons why you might get ModuleNotFoundError: No Module Named ‘Pandas’, and today’s article will go through all of them.

Table of contents:


How to Install Pandas with Pip and Anaconda

The ModuleNotFoundError — No Module Named ‘Pandas’ often occurs in PyCharm, VSCode, Jupyter, or any other IDE of your choice. The tool is ultimately irrelevant because it doesn’t cause the error — it only reports the result from the Python interpreter.

We already have extensive guides on How to install Pandas and How to install Pandas Specific version, so there’s no need to go into much depth here.

Simply, if you’re using Pip, run one of the following commands to install Pandas:

# To install the latest stable version of Panas
pip install pandas

# To install a specific version of Pandas, e.g., 1.3.4
pip install pandas==1.3.4

Likewise, if you’re using Anaconda, run either of these commands:

# To install the latest stable version of Panas
conda install pandas

# To install a specific version of Pandas, e.g., 1.3.4
conda install pandas=1.3.4

These commands will work 95% of the time, but if they don’t, continue reading to find the solution.


Other Causes of ModuleNotFoundError — No Module Named ‘Pandas’

We’ll now walk you through a series of potential reasons why you’re getting the No Module Named ‘Pandas’ error. Let’s start with the first, most obvious one.

Pandas Installed in a Virtual Environment, But You’re Accessing it Globally

We have a virtual environment named pandas-env which contains the latest development version of Pandas — 2.0.0RC1. This Pandas installation is specific to that environment and isn’t accessible outside it.

Take a look at the following image to verify:

Image 1 - Pandas version installed inside a virtual environment (Image by author)

Image 1 — Pandas version installed inside a virtual environment (Image by author)

If you were to deactivate this environment and import Pandas in a global (system-wide) one, you will get a ModuleNotFoundError — No Module Named ‘Pandas’ error:

Image 2 - ModuleNotFoundError - No Module Named &lsquo;Pandas&rsquo; error (Image by author)

Image 2 — ModuleNotFoundError — No Module Named ‘Pandas’ error (Image by author)


Solution: If you install Pandas inside a virtual environment, don’t forget to activate it before working with Pandas. Failing to do so is likely to result in a ModuleNotFoundError since global Python installation doesn’t know of the Pandas dependency.

You’ve Named Your Module ‘pandas.py’

Now, doing this could return all sorts of errors, ModuleNotFoundError being one of them.

Put simply, if you name your Python module pandas or if you create a file called pandas.py, you will shadow the actual library you’re trying to import.

To demonstrate, create two files in a folder — main.py and pandas.py. The contents of pandas.py are as follows:

# pandas.py

def sum_nums(a: int, b: int) -> int:
 return a + b

And the contents of main.py are:

# main.py

import pandas as pd

print(pd.__version__)

As you can see, main.py tries to import the Pandas library and print its version, but it imports the pandas.py file since it shadows the actual library. Running main.py would result in the following error:

Image 3 - Naming a file/module pandas.py (Image by author)

Image 3 — Naming a file/module pandas.py (Image by author)

Solution: Make sure your files and folders don’t have the same name as built-in Python libraries, nor the libraries you’ve installed manually, such as Pandas.

You’ve Declared a Variable ‘pandas’ By Accident

If you import the Pandas library and then somewhere in your script assign a value to a variable named pandas, that variable will shadow the library name.

By doing so, you won’t be able to access all the properties and methods Pandas library has to offer.

Take a look at the following snippet — it imports the Pandas library and then declares a variable pandas and assigns a string to it. You can still print out the contents of the variable, but you can’t access properties and methods from the Pandas library anymore:

# main.py
import pandas

pandas = "Don't do this!"

print(pandas)
print("----------")
print(pandas.__version__)

Image 3 - Declaring a variable named &lsquo;pandas&rsquo; (Image by author)

Image 3 — Declaring a variable named ‘pandas’ (Image by author)

Solution: Be a bit more creative with how you name your variables and make sure the name is different from any module you’ve imported.


No Module Named ‘Pandas’ Q&A

We’ll now go over some frequently asked questions about ModuleNotFoundError: No Module Named ‘Pandas’ error and the common solutions for them.

Q: How Do I Fix No Module Named Pandas?

A: First, make sure that Pandas is installed. Do so by running either pip install pandas or conda install pandas, depending on your environment. If that doesn’t work, try reinstalling Pandas by running the following sets of commands:

Pip:

pip uninstall pandas
pip install pandas

Anaconda:

conda uninstall pandas
conda install pandas

If neither of those works, make sure you don’t have a file/folder named pandas or pandas.py in your project’s directory, and make sure you haven’t named a variable pandas after importing the library.

Q: Why is it Showing No Module Named Pandas?

A: In case you’re using an IDE such as PyCharm, VSCode, or Jupyter, it’s possible the IDE is not recognizing your Python environment. Make sure the appropriate Python kernel is selected first.

A solution to ModuleNotFoundError — No Module Named ‘Pandas’ VSCode (Visual Studio Code):

Image 5 - VSCode solution (Image by author)

Image 5 — VSCode solution (Image by author)

A solution to PyCharm ModuleNotFoundError — No Module Named ‘Pandas’:

Image 6 - PyCharm solution (Image by author)

Image 6 — PyCharm solution (Image by author)

Q: Why I Can’t Install Pandas in Python?

A: One likely reason you can’t install Pandas in Python is that you don’t have administrative privileges on your system. For example, maybe you’re using a work or college computer and trying to install Pandas there. That system will likely be protected and it won’t allow you to install anything, Python modules included.

Another potential reason is that you’re maybe behind a corporate firewall. Before installing Pandas, configure the firewall settings manually to allow outgoing connections to the Internet, or talk to a company specialist.

Q: How Do I Know if Pandas is Installed?

A: You can verify if Pandas is installed on your system by opening up a Python interpreter and running the following code:

import pandas as pd

pd.__version__

If you don’t see any errors after the library import and if you see the version printed, then you have Pandas installed. Congratulations!

Here’s an example of what you should see:

Image 7 - Pandas installation check (Image by author)

Image 7 — Pandas installation check (Image by author)


Summing up

And there you have it, a list of many, many ways to install Pandas, and many potential issues and solutions you might encounter. As always, there’s no one-size-fits-all solution, but you’re more than likely to find an answer to ModuleNotFoundError: No Module Named ‘Pandas’ in this article.

Likely, you don’t have the library installed, but if that’s not the case, one of the other explained solutions is almost guaranteed to do the trick.

We hope you’ve managed to install Pandas properly, and can’t wait to see you in the following article.

Recommended reads

  • Top 10 Books to Learn Pandas in 2023 and Beyond

Понравилась статья? Поделить с друзьями:
  • Ps5 ошибка ce 118307 0
  • Ps5 ошибка ce 112025 1
  • Ps5 ошибка ce 105469 5
  • Ps5 ошибка ce 100005 6
  • Ps4 произошла ошибка su 42118 6