SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
Data Tools · Module 2Module material

pandas cheat sheet

Selecting, filtering, sorting, grouping, merging and reshaping a table with pandas: each question, the expression that answers it, and how to read the result. Free to read and share, no account needed.

The raw file has 2,921 rows and 11 columns. It includes one duplicate. The frozen clean file has 2,920 rows. Keep the files separate so every calculation states which one it uses.

QuestionExpressionRead it as
What is in the table?df.shape, df.info(), df.head()Size, types and first rows
One column?df["revenue"]A Series
Rows by label?df.loc[mask, ["date", "revenue"]]Label-based selection
Rows by position?df.iloc[:5, :3]First five rows, first three columns
Which rows?df.loc[df["weather"] == "rain"]Boolean selection
Sort largest first?df.sort_values("revenue", ascending=False)Rows reordered
Missing values?df.isna().sum()Count by column
Duplicates?df.duplicated().sum()Exact repeated rows
One total per shop?df.groupby("shop_id")["revenue"].sum()Eight values
One shop mean per row?df.groupby("shop_id")["revenue"].transform("mean")2,920 values
Add shop attributes?df.merge(shops, on="shop_id", validate="many_to_one")Match each sale to one shop
Days × shops?df.pivot(index="date", columns="shop_id", values="revenue")365 × 8 grid
Monthly totals?df.set_index("date")["revenue"].resample("MS").sum()Twelve values after parsing dates

Use pd.to_datetime(df["date"]) before time operations. MS means month start. loc uses index labels; iloc uses integer positions. After filtering or dropping rows, these can differ.

On the raw file, convert revenue with df["revenue"].str.replace(",", "", regex=False).astype(float). Normalize weather with .str.lower(). Check footfall < 0 before calling it a valid count. For missing temperature, say which imputation rule you chose; an imputed value is an estimate.

For assignment, use df.loc[mask, "column"] = value. The chained form df[mask]["column"] = value may write to a temporary object. Before any merge, decide whether the right-hand key is unique; validate="many_to_one" makes that expectation executable.

Glossary

  • DataFrame: Two-dimensional table with named columns and an index.
  • Series: One-dimensional labeled sequence, often a DataFrame column.
  • Index: Row labels; they are not guaranteed to equal row positions.
  • dtype: Type pandas assigns to a column. A successful import can still choose the wrong type for your calculation.
  • Boolean mask: One true/false value per row, used to keep matching rows.
  • loc / iloc: Selection by label / integer position.
  • Missing value: A cell with no recorded value, commonly represented by NaN or NA.
  • Sentinel: A special value, such as -1 footfall, that signals invalid or missing data but must be recognized explicitly.
  • Imputation: Filling a missing cell using a stated rule; it does not recover the unobserved fact.
  • Duplicate: A row repeated under a chosen equality rule; repeated dates alone are normal here because eight shops trade each day.
  • GroupBy: Split rows by key, perform a calculation per group, then combine results.
  • Aggregation: Reduce multiple rows to one result per group, such as a shop total.
  • Transform: Compute by group and return a value aligned to each original row.
  • Merge key: Column whose values pair rows across tables.
  • Join cardinality: Expected number of matches per key, such as many sales to one shop.
  • Pivot: Reshape long rows into indexed rows and columns.
  • Resample: Group observations into time intervals after dates are parsed and indexed.
  • Rolling window: Calculation over a moving set of neighboring time observations.