7 Modules and Packages

(CSE331) Python for Data Science

Author
Affiliation

Md Rasel Biswas

IASDS, University of Dhaka

1 Why Use Packages?

Python libraries provide reusable functions, constants, and classes. They allow us to perform common tasks without writing everything ourselves.

Tool Main purpose
math Mathematical functions and constants
statistics Basic summary statistics
NumPy Numerical arrays and calculations
pandas Tabular data analysis
Matplotlib Plotting
Seaborn Statistical visualization

A module is an importable unit of code, often a Python file. A package organizes related modules. Both are used through import.

math and statistics are modules in Python’s standard library and need no separate installation. NumPy, pandas, and the plotting libraries are third-party packages, although Anaconda may already include them.

2 Installing Packages

Installation makes a package available in a Python environment. Importing makes it accessible in the current Python session.

Normally, install once in the environment you use; import again whenever you start a fresh Python session or restart the notebook kernel.

2.1 Using pip in a notebook

Inside Jupyter, use %pip to install into the active kernel’s environment:

%pip install seaborn

Run installation commands manually when needed. They are not executed while rendering this lecture. Restart the kernel after installation if required.

2.2 Using pip in a terminal

pip is Python’s commonly used package installer. It is not a built-in Python function.

Run this in a terminal or Anaconda Prompt:

python -m pip install seaborn

Using python -m pip selects pip for that Python interpreter. On some systems the command is python3 -m pip.

Packages are commonly distributed through the Python Package Index (PyPI).

Task Terminal command
Install python -m pip install seaborn
Update python -m pip install --upgrade seaborn
Remove python -m pip uninstall seaborn
List installed packages python -m pip list
Show package details python -m pip show seaborn

2.3 Using Conda

Anaconda provides the conda package manager. In Anaconda Prompt or a terminal configured for Conda:

conda install numpy pandas matplotlib seaborn

Useful commands include:

conda update seaborn
conda list

Conda obtains packages from channels, which are package repositories. For example:

conda install -c conda-forge seaborn

Use the course’s existing environment and installation instructions. You do not need to install a package with both pip and Conda.

Installed, but import still fails?

A notebook can use a different Python environment from the terminal. Check the selected notebook kernel and the package name. Inside the notebook, %pip targets that kernel’s environment. Restart the kernel if needed.

3 Imports and Namespaces

Import a module, then access its contents using a dot:

import math
print(math.sqrt(25))
5.0

The name math refers to the imported module. The prefix makes it clear where sqrt() comes from and separates it from names in our own code.

pi = 3
print(pi)       # our variable
print(math.pi)  # the constant in math
3
3.141592653589793

Avoid assigning a new value to an imported module’s name, such as math = 5.

In R, qualified access such as stats::rnorm(5) similarly identifies which package provides the function. In Python, first import the module, then use the dot notation.

4 The math Module

import math

print(math.sqrt(20))
print(math.factorial(10))
print(math.exp(5))
print(math.log(10))    # natural logarithm
print(math.log10(100))
4.47213595499958
3628800
148.4131591025766
2.302585092994046
2.0

Constants and trigonometric functions:

print(math.pi)
print(math.sin(math.pi / 3))
print(math.cos(math.pi / 3))
print(math.tan(math.pi / 3))
3.141592653589793
0.8660254037844386
0.5000000000000001
1.7320508075688767

Trigonometric angles are in radians. These math functions operate on scalar numbers; NumPy will introduce array-oriented calculations.

5 Using Aliases

An alias gives an imported module a different local name:

import math as mt
print(mt.pi)
print(mt.sqrt(16))
3.141592653589793
4.0

For math, the original name is already short and clear. For data science libraries, the following aliases are conventional:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

matplotlib.pyplot is a module within Matplotlib. Aliases are conveniences, not requirements.

6 Importing Specific Objects

Use from ... import ... to make selected names available directly:

from math import pi, sin
print(pi)
print(sin(pi / 2))
3.141592653589793
1.0

An imported object can also receive an alias:

from math import pi as PI
print(PI)
3.141592653589793

This binds the selected names in the current namespace. It does not mean that only those pieces of the module are loaded. An imported name can replace a name you already defined: the earlier pi = 3 is replaced by from math import pi.

7 Importing All Exported Names

from math import *

A wildcard import brings the module’s exported names into the current namespace. It can overwrite existing names and make it difficult to see where a function came from. Prefer explicit imports.

It does not necessarily import every internal name in a module.

8 R and Python: A Short Comparison

Task R Python
Install install.packages("ggplot2") Terminal: python -m pip install matplotlib
Attach or import library(ggplot2) import matplotlib
Qualified access stats::median(x) statistics.median(x) after import statistics
Bind a function to a local name median_fn <- stats::median from statistics import median as median_fn
Inspect package metadata packageDescription("ggplot2") Terminal: python -m pip show matplotlib
List installed packages installed.packages() Terminal: python -m pip list or conda list

R’s library() attaches exported names to its search path. Python’s import normally keeps access under the module name. R’s pkg::fun accesses a function without creating a new local binding; Python’s from ... import ... creates such a binding.

9 Exercises

  1. Import math and calculate the square root of 81, the factorial of 6, and the natural logarithm of 10.
  2. Calculate the sine of \(\pi/6\) using math.sin().
  3. Repeat the square-root calculation using a module alias, then using a selective import.
  4. Explain the difference between installing a package and importing it. Which action is normally needed after restarting a kernel?
  5. Write the commands to install Seaborn from a notebook and from a terminal. Explain why the notebook’s environment matters.

10 Summary

  • The standard library is included with Python; third-party packages may require installation.
  • Use import module and module.object for clear access to imported tools.
  • Use conventional aliases where helpful and selective imports when appropriate.
  • Avoid wildcard imports.
  • Install into the environment used by your notebook, then import in each fresh session.

We are now ready to use NumPy, pandas, Matplotlib, and Seaborn. Data import and file handling will be introduced alongside the relevant data analysis tools.

11 Further reading