import pandas as pd
serves two functions. First, import pandas
tells Python to import the pandas library into the current programming environment. Second, as pd
tells Python that you want to give a nickname pd
for pandas
. That is, pd
will be alias for pandas
.
Example 1: Use import pandas as pd
# we import the pandas library and give it a nickname pd
import pandas as pd
# use the function of DataFrame()
df=pd.DataFrame({'Brand': ['Tesla', 'Ford'], 'Count': [3, 4]})
print(df)
Brand Count 0 Tesla 3 1 Ford 4
Note that, after using import pandas as pd
, you can not use pandas.DataFrame()
. The code below shows that it will have an error message of “name ‘pandas’ is not defined“.
import pandas as pd
df=pandas.DataFrame({'Brand': ['Tesla', 'Ford'], 'Count': [3, 4]})
print(df)
NameError: name 'pandas' is not defined
Example 2: Use import pandas
If you do not want to use pd
, you can just use the full name of pandas
in your code. Below is the example of using import pandas
.
# we import the pandas library
import pandas
# use the function of DataFrame()
df=pandas.DataFrame({'Brand': ['Tesla', 'Ford'], 'Count': [3, 4]})
print(df)
Brand Count 0 Tesla 3 1 Ford 4
Example 3: Use both pandas and pd at the same time
If you want to use both pandas and pd at the same time, you need to use both import pandas as pd
and import panda
s. Below is the example showing that.
# write out two statements
import pandas as pd
import pandas
# Using 'pd.DataFrame'
df_1=pd.DataFrame({'Brand': ['Tesla', 'Ford'], 'Count': [3, 4]})
print("Using 'pd.DataFrame':\n",df_1)
# Using 'pandas.DataFrame'
df_2=pandas.DataFrame({'Brand': ['Tesla', 'Ford'], 'Count': [3, 4]})
print("Using 'pandas.DataFrame':\n",df_2)
Using 'pd.DataFrame': Brand Count 0 Tesla 3 1 Ford 4 Using 'pandas.DataFrame': Brand Count 0 Tesla 3 1 Ford 4