1. Introducing (and importing) Packages and Modules#

Today, I’ll briefly introduce packages and how we import them WTOP Ch 14.

So far, we’ve mainly used base Python with a few peeks at functions not in base Python (e.g. sleep and plot). We can extend the functionality of our code by incorporating specialized modules or packages (a package is a collection of modules…we’ll just refer to everything as a package).

Packages may provide new data types and functions. We may choose to incorporate a package in its entirety or select only the functions we want.

The most common packages we’ll use moving forward in this course are:

  • numpy (alias np) - arrays and vectorized math, common math operations

  • pandas (alias pd) - dataframes and dataframe manipulation

  • matplotlib.pyplot (alias plt) - data visualization

  • sklearn - full name scikit-learn, modeling machine learning

You will also refer to the documentation for these packages frequently.

1.1. Importing Packages#

1.1.1. Importing entire packages#

We can import an entire package with:

import <package name>

Once imported, we can then use functions from the package as:

<package name>.<function>
import numpy
print(numpy.pi)
print(numpy.sin(numpy.pi/2))

vect = numpy.array([0, numpy.pi, 11.36])
print(vect)
3.141592653589793
1.0
[ 0.          3.14159265 11.36      ]

1.1.2. Importing with Aliases#

It will get tiring typing numpy every time you want to call a function from numpy. So it is common to abbreviate the package name by assigning it an alias. Some packages are so widely used, there is a conventional alias that everybody uses; in the list above, the common alias is in ().

We assign an alias at import using:

import <package name> as <alias>

and then to use functions from the package:

<alias>.<function>
import numpy as np
print(np.pi)
print(np.sin(np.pi/2))

vect = np.array([0, np.pi, 11.36])
print(vect)
3.141592653589793
1.0
[ 0.          3.14159265 11.36      ]

1.1.3. Importing Select Functions#

And sometimes, we may only need a few functions from a package, and we can import those individually.

from <package> import <f1>, <f2>

and then we can use these functions without prefix.

We import select functions when: - we really only need very few functions from a package - the package is very large and we don’t want to import the whole thing (sklearn for example)

from numpy import sin, cos, pi

print(cos(0))
print(sin(pi/2))
1.0
1.0