Python Modules

What is a Module?

Modules help group together related tools in Python. For example, we might want to group together all of the tools that make different types of charts: bar charts, line charts, and histograms. Some common examples of modules are matplotlib (which creates charts), pandas (which loads tabular data), scikit-learn (which perform machine learning), scipy (which contains statistics functions), and nltk (which work with text dat).

  • Groups related tools together.
  • Makes it easy to know where to look for a particular tool.

  • Common Examples:

    • matplotlib
    • pandas
    • scikit-learn
    • scipy
    • nltk

We must import any modules that we plan on using before we can write any other code. We do that at the top of the script editor. If we don't import modules, we can't use the tools that they contain.

Importing a Module

To import a module, simply type import followed by a space and then the module name.

import pandas

oftentimes, module names are long, so we can shorten them by using an alias. To give your module an alias, just add as and a shorter name to your original import statement.

import pandas as pd

Example

import pandas as pd
from matplotlib import pyplot as plt

By importing the modules pandas and matplotlib, we're able to unbox the tools necessary to create a graph. In this case, pandas gives us the tools to read data from a file, and matplotlib gives us the tools to plot the data.