Part 0. Importng Python Libraries#
As we have seen in previous lectures, Python runs code in modules called libraries.
Today we will explore three scientific computing libraries in Python: Numpy, Scipy, and Matplotlib. These libraries are widely used in data science, machine learning, and scientific computing for numerical computations, data manipulation, and visualization.
There are some libraries that come pre-installed with Python, but many others need to be installed separately. This is the case of all these three libraries. We need first to install, and then, import them in our code. Importing a library means making available all its functions and classes.
They are open-source and have extensive documentation and community support. They are also compatible with other popular Python libraries such as Pandas, Scikit-learn, and TensorFlow.
0.1 Installing Libraries#
We might have already installed these libraries if you are using the Anaconda environment we created the first week. But in case you need to install them, we can do so using conda or pip:
conda install numpy scipy matplotlib
pip install numpy scipy matplotlib
This applies to any other library you might want to install in the future. Just replace the library names with the ones you want to install. You can also install specific versions of the libraries by specifying the version number. For example, to install version 1.21.0 of Numpy, you can use:
### This is just an example
# This code runs in the terminal, not in Python
conda install numpy=1.21.0 scipy=1.7.0 matplotlib=3.4.2
# or
pip install numpy==1.21.0 scipy==1.7.0 matplotlib==3.4.2
0.2 Importing Libraries#
Once the libraries are installed, since they are not included in the standard Python library, we always need to import them in our Python script or Jupyter Notebook using the following commands:
# This code runs in Python
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
Here, we are importing Numpy as np, Scipy as sp, and Matplotlib’s pyplot module as plt. This is a common convention in the Python community and makes it easier to use the libraries in our code.
If you don’t load them in the beginning of your code, you will get an error when trying to use any of their functions or classes. The error will look like this:
NameError: name 'np' is not defined