Sub topic 2
Work with cells, modes, and shortcuts
Assume you know basic Python, can use a terminal, have Python 3 installed, and understand CSV files and tables. This chapter uses an existing virtual environment that contains JupyterLab, pandas, and matplotlib.
Work with cells, modes, and shortcuts
A Jupyter notebook is an interactive document made of cells. A code cell contains Python that the notebook sends to its kernel. A Markdown cell contains formatted notes, headings, or explanations.
Jupyter has two important modes:
- Command mode manages cells. Press
Escto enter it. - Edit mode edits the selected cell. Press
Enterto enter it.
Useful command-mode shortcuts include:
A: insert a cell above.B: insert a cell below.D,D: delete the selected cell.M: change the cell to Markdown.Y: change the cell to code.Shift+Enter: run the cell and select the next cell.Ctrl+Enter: run the cell and keep it selected.
The kernel is the Python process that executes cells and keeps variables in memory.
Register the environment as a kernel
A kernel specification connects Jupyter to a particular Python environment. From the activated project environment, register it with a clear name:
python -m ipykernel install --user --name data-analysis --display-name "Python (data-analysis)"In JupyterLab, choose Kernel > Change Kernel and select Python (data-analysis). Installing a package in one environment does not make it available to every kernel, so check the selected kernel before debugging import errors.
Meet pandas and matplotlib
pandas provides DataFrame, a table-like object for labeled rows and columns. matplotlib creates charts. Import both in a code cell:
import pandas as pd
import matplotlib.pyplot as pltLoad, inspect, and plot a dataset
Use read_csv to load a file. Then inspect its first rows, column types, missing values, and summary statistics.
df = pd.read_csv("data/sales.csv")
print(df.head())
df.info()
print(df.describe())
df["revenue"].plot(kind="hist", bins=20, title="Revenue distribution")
plt.xlabel("Revenue")
plt.show()df.info() reports column types and non-null counts. describe() summarizes numeric columns. A histogram groups values into bins, helping you see the distribution of revenue.
Exercise
Why might df["revenue"] fail even when the CSV loaded successfully?
Show answer
The file may use a different column name, capitalization, or spacing. Check df.columns before selecting the column.