Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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.
Open your terminal in your project's root directory and install the pandas
module.
# 👇️ 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.
# ✅ 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.
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.