Sub topic 9
Speed up your workflow with magic commands
This chapter assumes you have a working virtual environment with JupyterLab, pandas, and matplotlib installed, and that you can run cells in a notebook. You should know basic Python syntax.
What magic commands are
Magic commands are special commands that IPython, the interactive Python shell behind the Jupyter kernel, adds on top of normal Python. They are not valid Python syntax, so they only work inside a notebook or IPython session. There are two kinds:
- Line magics start with one
%and act on the rest of that line. - Cell magics start with
%%and act on the whole cell. They must be on the first line of the cell.
Magics change how your notebook behaves, so they are worth learning early. This chapter covers the two you will use in almost every data analysis notebook.
Show plots inside the notebook
Put this line near the top of the notebook:
%matplotlib inlineThis tells matplotlib to render figures as images directly below the cell that created them. Recent JupyterLab and ipykernel versions already use this behavior by default, so the line is often redundant. It is still common in shared notebooks, and it makes your intent explicit.
You can still call plt.show() after a plot. It is good practice, because it also works when the code is later moved into a script.
Reload your own modules automatically
As a project grows, you will move reusable code from the notebook into .py files. Python imports a module only once per kernel session. If you edit the file afterward, the notebook keeps using the old version until you restart the kernel.
The autoreload extension fixes this:
%load_ext autoreload
%autoreload 2%load_ext autoreloadloads the extension into the current kernel.%autoreload 2reloads all imported modules before each cell runs.
Here is a small example. Create a file named helpers.py next to your notebook:
def clean_columns(df):
df = df.copy()
df.columns = [c.strip().lower().replace(" ", "_") for c in df.columns]
return dfIn the notebook, run the autoreload lines and then import the function:
%load_ext autoreload
%autoreload 2
import pandas as pd
from helpers import clean_columns
df = clean_columns(pd.DataFrame({"Total Revenue ": [10, 20]}))
print(df.columns.tolist())The output is ['total_revenue']. Now edit helpers.py, for example to add .replace("-", "_"), save it, and re-run the last cell. The new code runs without a kernel restart.
Other useful magics
| Magic | What it does |
|---|---|
| `%lsmagic` | Lists all available magics |
| `%timeit expr` | Times a single expression over many runs |
| `%%time` | Times the whole cell once |
| `%who` | Lists variables defined in the session |
| `%pwd` | Prints the current working directory |
Add ? after a magic name, such as %timeit?, to read its documentation.
Common errors
UsageError: Line magic function '%autoreload' not found. You ran%autoreload 2before%load_ext autoreload. Run the load line first.- A cell magic does nothing or raises a syntax error.
%%magics must be the very first line of the cell. A comment or blank line above it breaks it. - Changes to a module are ignored. Autoreload works on modules you import, not on code in notebook cells. It also cannot update objects that were created before the edit, such as instances of a class you changed. Create the object again after editing.
- Magics in exported scripts. Magic lines are not valid Python. If you export a notebook to a
.pyfile, they are converted toget_ipython()calls, which fail outside IPython.
Where magics fit in the workflow
Magics are best placed in the first code cell, together with your imports. That cell then acts as a setup step you can find quickly, which also helps when you restart the kernel and run all cells in order.
Exercise
You edit a function in helpers.py, save the file, and re-run a notebook cell that calls it. The cell still shows the old behavior. The notebook has no autoreload lines. Name two ways to get the new code running.
Show answer
Either restart the kernel and run the cells again, or run %load_ext autoreload followed by %autoreload 2 and then re-run the cell. Autoreload only affects modules imported after it is enabled, so you may need to re-import the module or create any existing objects again.