Python Import – Bring In Another Library

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.

>>>NameError: name 'pandas' is not defined
import pandas

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

Python Import

In order to take advantage of other libraries, you'll need to import them to python.

Import means "Hey! Go grab this code from another place and bring it in my program so we can use it"

Let's look at an example with the data analysis library, Pandas.

In [1]:
pandas.DataFrame(index=[1,2,3], data=[[1,2], [2,3], [3,4]], columns=['col1', 'col2'])
NameError                                 Traceback (most recent call last)
<ipython-input-1-6ea256d3dd2f> in <module>
----> 1 pandas.DataFrame(index=[1,2,3], data=[[1,2], [2,3], [3,4]], columns=['col1', 'col2'])

NameError: name 'pandas' is not defined

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

In [2]:
import pandas
In [3]:
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.

In [5]:
import pandas as pd
In [6]:
pandas.DataFrame(index=['Bob','Sally', 'Ted'], data=[[10,22], [23,35], [31,46]], columns=['Col_1', 'Col_2'])

Link to code above

Check out more Python Vocabulary on our Glossary Page