A python library is a collection of functions and methods that allows you to perform many actions without writing your own code.
We have already encountered and learned to use some of the popular libraries: numpy, pandas, matplotlib, and seaborn.
Many libraries come installed with anaconda including both pandas and seaborn. However, these libraries are not imported when you open a jupyter notebook, so we have to tell python which libraries we would like to use.
Importing Libraries
The most basic way to import a libary is to use import. The syntax of importing a library is like
import library_name
We can also use as to give an alias.
import library_name as alias
Now the library can be accessed using the alias. We have already used this approach when importing libraries like pandas, numpy, matplotlib, and seaborn.
import numpy as npimport pandas as pdimport seaborn as sns
---------------------------------------------------------------------------ModuleNotFoundError Traceback (most recent call last)
CellIn[1], line 3 1importnumpyasnp 2importpandasaspd----> 3importseabornassnsModuleNotFoundError: No module named 'seaborn'
In the previous lectures we have used pandas data frames. When using a module within a library we use it after the library name and a dot. For example, pd.DataFrame or np.array.
What if we want to use only the specific functions/classes within a module? In that case, we can use from library import function. For example, we want to use the permutation function from numpy.
In that case we can do
from numpy.random import permutation
Now we can use the permutation function like we use other functions.
permutation(list(range(10)))
array([6, 8, 0, 9, 1, 3, 5, 4, 7, 2])
Hopefully, you can see how importing data from and exporting data to csv or other delimiter separated files will be helpful for research. Now it’s time to practice your skills with built-in data structures and data frames!
Python ecosystem
One reason why python is such a powerful language is because of the python ecosystem (especially for data science).
Installing libaries
Now, what if we want to use a new library? In this part, we will learn how to install new libraries. In python, there are package managers like pip and conda that will make your life easier when installing and removing python libraries. You can go to your terminal and type in:
where pip3
to ensure you have pip3 (pip for Python 2) on your machine.
The standard way of installing library with pip is:
python3 -m pip install "library name"
Another awesome and popular package manager is Anaconda. Anaconda can be easily installed on to your local machine (windows, linux, and mac) from their website.