Fix - NameError: name 'pandas' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

Fix - NameError: name 'pandas' is not defined in Python #

The Python "NameError: name 'pandas' is not defined" occurs when we use the pandas module without importing it first. To solve the error, install the module and import it (import pandas) before using it.

nameerror name pandas is not defined

Open your terminal in your project's root directory and install the pandas module.

shell
# 👇️ in a virtual environment or using Python 2 pip install pandas # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install pandas # 👇️ if you get permissions error sudo pip3 install pandas # 👇️ if you don't have pip in your PATH environment variable python -m pip install pandas # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install pandas # 👇️ for Anaconda conda install -c anaconda pandas

After you install the pandas module, make sure to import it before using it.

main.py
# ✅ import pandas first import pandas df = pandas.DataFrame( { "Name": [ "Alice", "Bob", "Carl", ], "Age": [29, 30, 31], } ) print(df)
Make sure you haven't used a capital letter p when importing pandas because module names are case-sensitive.

Also, make sure you haven't imported pandas in a nested scope, e.g. a function. Import the module at the top level to be able to use it throughout your code.

Note that the pandas module is often aliased to pd in import statements.

main.py
import pandas as pd df = pd.DataFrame( { "Name": [ "Alice", "Bob", "Carl", ], "Age": [29, 30, 31], } ) print(df)

The import statement imports the pandas module and aliases it to pd, so we access the module's classes as pd.DataFrame, pd.Series, etc.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.