Ошибка import pandas as pd

I can’t seem to import panda package. I use Visual Studio code to code. I use a mac and have osX 10.14 Majove.

The code that i am trying to compile is :

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
house_data = pd.read_csv('house.csv')
plt.plot(house_data['surface'], house_data['loyer'], 'ro', markersize=4)
plt.show()

When I try to use pip install pandas i get on my terminal :

(base)  pip install pandas
Requirement already satisfied: pandas in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (0.24.0)
Requirement already satisfied: pytz>=2011k in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2018.9)
Requirement already satisfied: python-dateutil>=2.5.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2.7.5)
Requirement already satisfied: numpy>=1.12.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (1.15.3)
Requirement already satisfied: six>=1.5 in /Users/Library/Python/3.7/lib/python/site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)
(base) Thibaults-MBP-5d47:ML_folder thibaultmonsel$

Then when i execute my code i get :

Traceback (most recent call last):
  File "ML1.py", line 5, in <module>
    import pandas as pd
ImportError: No module named pandas

After if i try sudo pip install pandas i get :

(base) MBP-5d47:ML_folder $ sudo pip3 install pandas --upgrade
Password:
The directory '/Users/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory.If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/34/63/529fd1391044051514f2f22d61754245db2133cd37c4dad7150a1cbe2ece/pandas-0.24.1-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (15.9MB)
    100% |████████████████████████████████| 15.9MB 901kB/s
Requirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2.7.5)
Requirement already satisfied, skipping upgrade: numpy>=1.12.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (1.15.3)
Requirement already satisfied, skipping upgrade: pytz>=2011k in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2018.9)
Requirement already satisfied, skipping upgrade: six>=1.5 in /Users/Library/Python/3.7/lib/python/site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)
Installing collected packages: pandas
  Found existing installation: pandas 0.24.0
    Uninstalling pandas-0.24.0:
      Successfully uninstalled pandas-0.24.0
Successfully installed pandas-0.24.1

However, i still get no modules named pandas

Lastly, when i try pip3 install pandas i get :

Requirement already satisfied: pandas in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (0.24.0)
Requirement already satisfied: pytz>=2011k in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2018.9)
Requirement already satisfied: numpy>=1.12.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (1.15.3)
Requirement already satisfied: python-dateutil>=2.5.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pandas) (2.7.5)
Requirement already satisfied: six>=1.5 in /Users/Library/Python/3.7/lib/python/site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)

When i try to execute the program i get the same error mentioned above after using pip3 install pandas….

I also did an import.sys if can help :

base)-MBP-5d47:ML_folder $ python help1.py
2.7.10 (default, Aug 17 2018, 17:41:52)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)]

Here is also my sys.path :

['/Users/Desktop/ML_folder', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']


Одна распространенная ошибка, с которой вы можете столкнуться при использовании Python:

NameError : name 'pd' is not defined

Эта ошибка обычно возникает, когда вы импортируете библиотеку python pandas , но не можете указать псевдоним pd при импорте.

Следующие примеры иллюстрируют, как эта ошибка возникает на практике и как ее можно быстро исправить.

Пример 1: Используйте импорт pandas как pd

Предположим, вы импортируете библиотеку pandas, используя следующий код:

import pandas

Если вы затем попытаетесь создать pandas DataFrame, вы получите следующую ошибку:

#create pandas DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#attempt to print DataFrame
print(df)

Traceback (most recent call last):
 1 import pandas
----> 2 df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 3 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 4 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
 5 

NameError : name 'pd' is not defined

Чтобы исправить эту ошибку, вам нужно указать псевдоним pd при импорте pandas.

import pandas as pd

#create pandas DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#print DataFrame
print(df)

 points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12

Пример 2: Используйте импортные Pandas

Предположим, вы импортируете библиотеку pandas, используя следующий код:

import pandas

Если вы затем попытаетесь создать pandas DataFrame, вы получите следующую ошибку:

#create pandas DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#attempt to print DataFrame
print(df)

Traceback (most recent call last):
 1 import pandas
----> 2 df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 3 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 4 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
 5 

NameError : name 'pd' is not defined

Чтобы исправить эту ошибку, вы можете просто вообще не использовать псевдоним pd :

import pandas

#create pandas DataFrame
df = pandas. DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#print DataFrame
print(df)

 points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12

Примечание. Обычно используется синтаксис «импортировать pandas как pd», поскольку он предлагает более лаконичный способ использования функций pandas. Вместо того, чтобы каждый раз вводить «Pandas», вы можете просто ввести «pd», который быстрее и легче читается.

Дополнительные ресурсы

Как исправить: нет модуля с именем pandas
Как исправить: имя NameError ‘np’ не определено

I got this error message. Already installed pandas.

>>> import pandas as pd
Traceback (most recent call last):
  File "analyze_tweets.py", line 9, in <module>
    import pandas as pd 
ImportError: No module named pandas

SOLUTION (by @datapythonista)

This error happens when Python can’t find pandas in the list of available libraries. Python has internally a list of directories where it’ll look for packages. These directories can be obtained with import sys; sys.path.

In one machine you can (and should) have several Python installations. Meaning that you can have pandas installed in one, and be using another Python installation (this is likely the case here).

In Linux/Mac you can run which python and will tell you which is the Python you’re using. If it’s something like /usr/bin/python, you’re using the Python from the system, which is not a great practice, and rarely used in the Python community.

If you used Python before you may have used virtual environments and pip. While this is fine for many Python projects (e.g. Django), when using data projects (pandas, numpy, tensorflow…) this is discouraged. It’s easy that you have installation errors, and also the libraries can run much slower when using pip.

The widely used solution to this problem is to use conda. You can find simple installation instructions for pandas in this document: https://dev.pandas.io/getting_started.html

For more advanced users, installing miniconda, and then manually install pandas (and any other required package) with conda can be preferred (but avoid this if you’re starting, since you’ll probably have errors of missing dependencies when using many of the pandas features).

In this article, we will discuss how to fix the No module named pandas error.

The error “No module named pandas ” will occur when there is no pandas library in your environment IE the pandas module is either not installed or there is an issue while downloading the module right.

Let’s see the error by creating an pandas dataframe.

Example: Produce the error

Python3

import pandas

pandas.DataFrame({'a': [1, 2]})

Output:

We will discuss how to overcome this error. In python, we will use pip function to install any module

Syntax:

pip install module_name

So we have to specify pandas

Example: Installing Pandas 

Python3

Output:

Collecting pandas

  Downloading pandas-3.2.0.tar.gz (281.3 MB)

     |████████████████████████████████| 281.3 MB 9.7 kB/s 

Collecting py4j==0.10.9.2

  Downloading py4j-0.10.9.2-py2.py3-none-any.whl (198 kB)

     |████████████████████████████████| 198 kB 52.8 MB/s 

Building wheels for collected packages: pandas

  Building wheel for pandas (setup.py) … done

  Created wheel for pandas: filename=pyspark-3.2.0-py2.py3-none-any.whl size=281805912 sha256=c6c9edb963f9a25f31d11d88374ce3be6b3c73ac73ac467ef40b51b5f4eca737

  Stored in directory: /root/.cache/pip/wheels/0b/de/d2/9be5d59d7331c6c2a7c1b6d1a4f463ce107332b1ecd4e80718

Successfully built pandas

Installing collected packages: py4j, pandas

Successfully installed py4j-0.10.9.2 pandas-3.2.0

We can verify by again typing same command then the output will be:

Output:

Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.1.5)

To get the pandas description in our environment we can use the show command. This can help keep track of the module and its installation.

Example: Show module description 

Python3

Output:

Name: pandas

Version: 1.1.5

Summary: Powerful data structures for data analysis, time series, and statistics

Home-page: https://pandas.pydata.org

Author: None

Author-email: None

License: BSD

Location: /usr/local/lib/python3.7/dist-packages

Requires: numpy, python-dateutil, pytz

Required-by: xarray, vega-datasets, statsmodels, sklearn-pandas, seaborn, pymc3, plotnine, pandas-profiling, pandas-gbq, pandas-datareader, mlxtend, mizani, holoviews, gspread-dataframe, google-colab, fix-yahoo-finance, fbprophet, fastai, cufflinks, cmdstanpy, arviz, altair

Upgrade Pandas

Upgrading pandas is the best advantage to get error-free in your environment. So, we have to upgrade using the following command.

Example: Upgrading Pandas

Python3

pip3 install pandas - -upgrade

Output:

Install Specific version

To install a specific version of pandas we have to specify the version in the pip command.

Example: Installing a specific version of a module

Python3

pip3 install pandas == 1.3.4

Output:

Find the version

If we want to find the version then we have to use __version__

Syntax:

module_name.__version__

Example: Get pandas version

Python3

import pandas as pd

pd.__version__

Output:

1.1.5

Last Updated :
19 Dec, 2021

Like Article

Save Article

Table of Contents
Hide
  1. Solution NameError: name ‘pd’ is not defined
    1. Method 1 – Importing pandas with Alias as pd
    2. Method 2 – Importing all the functions from pandas
    3. Method 3 – Importing pandas package without an alias

In Python,  NameError: name ‘pd’ is not defined occurs when you import the pandas library but fail to provide the alias as pd while importing it.

In this article, let us look at what is NameError name pd 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 pandas library and created a pandas DataFrame.

# import pandas library
import pandas 
import numpy as np

# create pandas DataFrame
df =  pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])

# print dataframe
print(df)

Output

Traceback (most recent call last):
  File "C:PersonalIJSCodemain.py", line 6, in <module>
    df =  pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
NameError: name 'pd' is not defined. Did you mean: 'id'?

When we run the code, we get  NameError: name ‘pd’ is not defined  since we did not provide an alias while importing the pandas library.

There are multiple ways to resolve this issue. Let us look at all the approaches to solve the NameError.

Method 1 – Importing pandas with Alias as pd

The simplest way to resolve this error is by providing an alias as pd while importing the pandas library. Let’s fix our code by providing an alias and see what happens.

# import pandas library
import pandas as pd
import numpy as np

# create pandas DataFrame
df =  pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])

# print dataframe
print(df)

Output

   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

The syntax “import pandas as pd” is commonly used because it offers a more concise way to call pandas functions, and the code is more readable as we do not have to type “pandas” each time.

Method 2 – Importing all the functions from pandas

There might be a situation where you need to import all the functions from the pandas library, and to do that, we will be using the below syntax.

from pandas import *

In this case, you do not need any reference to call any functions of pandas. You can directly call the methods without using an alias, and in this example we can directly create the DataFrame as shown below.

# import pandas library
from pandas import *
import numpy as np

# create pandas DataFrame
df =  DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])

# print dataframe
print(df)

Output

   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Method 3 – Importing pandas package without an alias

Another way is to import a complete pandas package and call the functions directly with the pandas name without defining an alias.

# import pandas library
import pandas
import numpy as np

# create pandas DataFrame
df =  pandas.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])

# print dataframe
print(df)

Output

   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

In the above example, we import the complete pandas library and use pandas.DataFrame() method to create pandas DataFrame.

Note: If you are running the code in Jupyter notebook, ensure that you run the cell where you have imported the pandas and then run the rest of the code.

Понравилась статья? Поделить с друзьями:
  • Ошибка igoproxy64 exe
  • Ошибка ignition lock faulty порше
  • Ошибка igdkmd64 sys windows 10
  • Ошибка http code 1 телевизор
  • Ошибка http 401 unauthorized