Skip to content
Related Articles

Related Articles

How to Fix: NameError name ‘pd’ is not defined

Improve Article
Save Article
Like Article
  • Last Updated : 28 Nov, 2021

In this article we will discuss how to fix NameError pd is not defined in Python.

When we imported pandas module without alias and used pd in the code, the error comes up.

Example: Code to depict error

Python3




# import pandas module
import pandas
  
# create dataframe
data = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  
# display
data

Output:

—————————————————————————

NameError                                 Traceback (most recent call last)

<ipython-input-1-a37aacbaa7a7> in <module>()

      3 

      4 #create dataframe

—-> 5 data=pd.DataFrame({‘a’:[1,2],’b’:[3,4]})

      6 

      7 #display

NameError: name ‘pd’ is not defined

Here pd is an alias of the pandas module so we can either import pandas module with alias or import pandas without the alias and use the name directly.

Method  1: By using the alias when importing the pandas

we can use alias at the time of import to resolve the error

Syntax:

import pandas as pd

Example: Program to import pandas as alias

Python3




# import pandas module
import pandas as pd
  
# create dataframe
data = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  
# display
data

Output:

    a    b
0    1    3
1    2    4

Method 2: Use pandas directly

We can use pandas module directly to use in a data structure.

Syntax:

import pandas

Example: Using Pandas directly

Python3




# import pandas module
import pandas
  
# create dataframe
data = pandas.DataFrame({'a': [1, 2], 'b': [3, 4]})
  
# display
data

Output:

    a    b
0    1    3
1    2    4

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!