Libraries

Libraries#

You’ll quickly hit a ceiling in Python’s usefulness if you can’t import external libraries. What if you want the value of \(\pi\)? A TI-34 calculator would have a button for this number. In Python, we have to import a library like NumPy (short for Numerical Python). If a library is already installed, you can simply import it with a line like import numpy. Because pi is already defined within NumPy, we can then access the value with numpy.pi.

import numpy

numpy.pi
3.141592653589793

Note that pi was prefixed with numpy above. Because prefixing can be cumbersome, a library is sometimes aliased so that the prefix can be abbreviated. Below, we use the typical np alias.

import numpy as np

np.pi
3.141592653589793

Next, suppose you have a \(z\)-score of 1.8 and you want to know what percentile that corresponds to. You can use a table, but this is a task best suited for a computer.

To do this, we import the SciPy library, which includes a specific function that substitutes for a \(z\)-table.

Once we run import scipy, SciPy’s capabilities are available to us. It so happens that the function we want is norm.cdf from the stats submodule.

import scipy

z = 1.8
scipy.stats.norm.cdf(z) # The area to the left of z under a standard normal curve
np.float64(0.9640696808870742)

Below, we import just the stats submodule and alias it as stats to shorten the code.

import scipy.stats as stats

z = 1.8
stats.norm.cdf(z) # The area to the left of z under a standard normal curve
np.float64(0.9640696808870742)

This can be shortened further if we import just the norm object using the syntax below. None of these SciPy imports are clearly better than the others for our purposes. You’ll see there are many ways to code the same thing and you’ll find code online using all of these conventions.

from scipy.stats import norm
norm.cdf(z)
np.float64(0.9640696808870742)