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
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