Last modified: Mar 05, 2025 By Alexander Williams

Fix Python NameError: Name 'pd' Not Defined

If you're working with Python, especially in data analysis, you might encounter the error: NameError: Name 'pd' Not Defined. This error occurs when Python cannot recognize the name pd. Let's explore why this happens and how to fix it.

What Causes the NameError: Name 'pd' Not Defined?

The error typically occurs when you try to use pd without importing the Pandas library. In Python, pd is a common alias for the Pandas library. If you forget to import Pandas or misspell the alias, this error will appear.

Here’s an example of code that would trigger this error:


# Missing Pandas import
data = pd.DataFrame({'A': [1, 2, 3]})
    

NameError: name 'pd' is not defined
    

How to Fix the NameError: Name 'pd' Not Defined

To fix this error, you need to import the Pandas library and assign it the alias pd. Here’s how you can do it:


import pandas as pd  # Correct import statement
data = pd.DataFrame({'A': [1, 2, 3]})
print(data)
    

   A
0  1
1  2
2  3
    

By importing Pandas as pd, the code runs without errors. Always ensure that you import libraries before using them.

Common Mistakes to Avoid

Here are some common mistakes that lead to this error:

  • Forgetting to import Pandas: Always include import pandas as pd at the beginning of your script.
  • Misspelling the alias: Ensure you use pd consistently. Using pandas instead of pd will also cause errors if you don’t adjust your code accordingly.
  • Importing in the wrong scope: If you import Pandas inside a function, pd won’t be available outside that function.

For more tips on fixing similar errors, check out our guide on Fix Python NameError: Name 'json' Not Defined.

Example: Using Pandas in a Function

If you import Pandas inside a function, pd will only be available within that function. Here’s an example:


def create_dataframe():
    import pandas as pd  # Import inside the function
    data = pd.DataFrame({'A': [1, 2, 3]})
    return data

print(create_dataframe())
    

   A
0  1
1  2
2  3
    

If you try to use pd outside the function, you’ll get the NameError again. Always import libraries at the script level unless you have a specific reason not to.

Conclusion

The NameError: Name 'pd' Not Defined is a common issue for Python beginners. It occurs when you forget to import the Pandas library or misspell the alias. By ensuring proper imports and avoiding common mistakes, you can easily fix this error.

For more help with Python errors, check out our guides on Fix Python NameError: Name 'cursor' Not Defined and Fix Python NameError: Name 'df' Not Defined.