Sub topic 7
Meet pandas and matplotlib in a notebook
This chapter assumes you have a working virtual environment with JupyterLab, pandas, and matplotlib installed, and that your environment is registered as a kernel. It also assumes you can run cells and know basic Python syntax. Here you will see what each library does and how they work together inside a notebook.
What each library does
pandas holds and transforms tabular data. Its central object is the DataFrame, a table with labeled columns and a row index. A single column is a Series.
matplotlib draws charts. pandas calls matplotlib for you when you use .plot(), so the two libraries share one workflow: pandas prepares the data, and matplotlib renders it.
| Library | Main object | Typical job |
|---|---|---|
| pandas | `DataFrame`, `Series` | Load, filter, group, summarize |
| matplotlib | `Figure`, `Axes` | Draw and style charts |
Confirm the kernel can import both
Open a new notebook and pick the kernel you registered, "Python (data-analysis)". Then run this in the first cell:
import pandas as pd
import matplotlib.pyplot as plt
print(pd.__version__)
print(plt.matplotlib.__version__)If both versions print, the notebook is using the environment where you installed the libraries. If you see ModuleNotFoundError, the notebook is running a different kernel. Check the kernel name in the top-right corner of the notebook and switch it.
The names pd and plt are community conventions. Use them so your code matches nearly every example you will read.
Build a small DataFrame
You do not need a file to try pandas. Create a table directly from a dictionary:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"region": ["North", "South", "East", "West"],
"revenue": [1200, 950, 1430, 780],
})
dfWhen a cell's last line is an expression, the notebook displays its value. A DataFrame appears as a formatted HTML table. This is different from print(df), which gives plain text. In a notebook, ending a cell with the variable name is the usual way to look at data.
Select and compute
Use square brackets with a column name to get a Series. Methods on that Series compute summaries:
total = df["revenue"].sum()
best = df.loc[df["revenue"].idxmax(), "region"]
print(total)
print(best)A boolean condition inside the brackets filters rows:
df[df["revenue"] > 1000]Each of these operations returns a new object. They do not change df unless you assign the result back to a name.
Plot from the DataFrame
Call .plot() on a column or on the whole table. The kind argument picks the chart type.
df.plot(x="region", y="revenue", kind="bar", legend=False)
plt.title("Revenue by region")
plt.ylabel("Revenue")
plt.show()df.plot() returns an Axes object, which is matplotlib's name for the area containing one chart. The plt.title and plt.ylabel calls act on the current chart. Calling plt.show() at the end of the cell finishes the figure and displays it below the cell.
Common errors
NameError: name 'df' is not defined. The cell that createsdfhas not run in this kernel session. Run it first, or restart the kernel and run all cells in order.KeyError: 'revenue'. The column name does not match exactly. Checkdf.columns. Names are case-sensitive, and stray spaces in CSV headers are common.- No chart appears. Make sure the cell calls
plt.show(), or that you ran the%matplotlib inlinemagic covered in a later chapter. - Plot shows up in an old cell. Each
plt.show()closes the current figure. Without it, laterpltcalls can draw onto the same figure.
Exercise
A cell contains df[df["revenue"] > 1000] and runs without error, but a later cell that prints df still shows all four rows. Why?
Show answer
Filtering returns a new DataFrame and leaves df unchanged. To keep the filtered result, assign it to a name, for example big = df[df["revenue"] > 1000], or reassign df itself.
Exercise
You run import pandas as pd in a notebook and get ModuleNotFoundError: No module named 'pandas', although pip install pandas succeeded in your terminal. What is the most likely cause, and how do you check?
Show answer
The notebook is using a different kernel than the environment where pandas was installed. Check the kernel name shown at the top right of the notebook and switch it to "Python (data-analysis)". You can also run import sys; print(sys.executable) in a cell to see which Python the kernel uses.