Packages

In computer programming, a package is a collection of modules or programs that are often published as tools for a range of common use cases, such as text processing and doing math. Programmers can install these packages and take advantage of their functionality within their own code.

This page provides instructions for installing, using, and troubleshooting packages in Python.

Installing and Loading Packages

There is a two-step process for using an external package in Python. First, if it is your first time using the package, you must install the package. This only needs to be done once for the environment you are working in, even if you are using different documents or files. Then, you must load the package to your specific document. Let's look at an example using the NumPy package

Installing Packages Syntax

To install a package, we use the pip command as follows:

pip install numpy

Again note that this only needs to be done once. After you have installed a package you do not need to do so again, you can simply load it

Loading Packages

If we want to load an entire package (instead of just certain functions), we can use the import command as follows:

import numpy as np

We import the name of the package and name is as some shorthand name so that we do not need to type the whole package name every time we want to use a function from that package. In order to call a function from an imported package we can use the shorthand name followed by a dot followed by the name of the function. Here is an example:

# Creating an array
array1 = np.array([1, 2, 3, 4, 5])

# Getting the mean of the values in our array
mean = np.mean(array1)  

Module-Based Packages

Some packages will have many different parts, or modules, and we might not want to use all of these modules at once. Importing all of these modules when we don't need them can be an unnecessary waste of computing power, so instead we can only import the functions we need. Let's look at the scikit-learn package for example

Scikit-Learn

We can install this package the same way as above, however we will not import the whole package at once. Instead, we will only import the functions we need from the modules we need. Here is an example of how we can import the train_test_split() function from the model_selection module of scikit-learn (or sklearn for short)

from sklearn.model_selection import train_test_split

Last updated