In Python, you’ll often want to bring in other pieces of code. This could be code that you wrote, or someone else wrote. The most basic case is bringing in other libraries. In order to do this, you’ll need to import
.
pandas.DataFrame() >>>NameError: name 'pandas' is not defined import pandas pandas.DataFrame() >>>Nice!
Python Import
Once you import a library, it’s name will be a part of your python namespace. These are the keywords that python will recognize and and execute.
However, if your library name is long, like matplotlib, then you may want to have a shorthand way to reference the code. This is where the keyword as
comes in.
If you follow your import
statement with as
you’ll have a new, shorter name for your library.
Let’s look at a quick code sample
pandas.DataFrame(index=[1,2,3], data=[[1,2], [2,3], [3,4]], columns=['col1', 'col2'])
Oh no! Pandas isn't defined. This means that python doesn't know what the word 'pandas' is. We need to import the pandas library in order to use it
import pandas
pandas.DataFrame(index=[1,2,3], data=[[1,2], [2,3], [3,4]], columns=['col1', 'col2'])
nice, we can use it finally. But typing out 'pandas' each time is a little long. I'm going to add an abbreviation to call pandas 'pd' for short via the as keyword. Then I can use pd. instead of pandas.
import pandas as pd
pandas.DataFrame(index=['Bob','Sally', 'Ted'], data=[[10,22], [23,35], [31,46]], columns=['Col_1', 'Col_2'])
Check out more Python Vocabulary on our Glossary Page