Open In App

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

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




# 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




# 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




# 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

Article Tags :