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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

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

The Python "NameError: name 'pd' 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 as pd) 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 and alias it as pd 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.

Make sure you haven't misspelled pandas and are using all lowercase letters 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.

If the error persists after importing pandas as pd, restart your IDE and development server.

Use the search field on my Home Page to filter through my more than 1,000 articles.