Pandas Cheat Sheet for pandas 3: Commands With Worked Outputs

Every everyday pandas command (read, inspect, loc and iloc, filter, clean, groupby, merge, pivot, resample) run on one sensor dataset with its real output, checked on pandas 3.1.1. Plus what pandas 3.0 removed, and how to cut string memory by up to 56 times.

Pandas Cheat Sheet for pandas 3: Commands With Worked Outputs

This pandas cheat sheet lists the commands you use every day (read, inspect, select, filter, clean, group, merge, reshape, resample) and runs each one on the same small machine-sensor dataset, so you see the real output, not just the syntax. Every example was run on pandas 3.1.1, the current release (4 November 2026). It also flags the old commands that pandas 3.0 removed, such as applymap, append and the "M" frequency, which still fill older cheat sheets.

Key takeaways

  • Current version: pandas 3.1.1, released 4 November 2026 (PyPI). pandas 3.0.0 came out on 21 January 2026 and needs Python 3.11 or newer.
  • Copy-on-Write is always on in pandas 3. Chained assignment such as df["a"][mask] = 0 no longer changes df; it only raises a ChainedAssignmentError warning. Use df.loc[mask, "a"] = 0.
  • Text columns now show str, not object. With PyArrow installed, one million short strings took 15.6 MB as str against 56.6 MB as object in our test; as category, 1.0 MB.
  • Removed in pandas 3: DataFrame.applymap (use map), the "M", "Q", "Y" and "H" aliases (use "ME", "QE", "YE", "h"). append went in 2.0 (use pd.concat).
  • pandas is everywhere: about 701 million downloads from PyPI in the month to 22 November 2026 (pypistats.org).

Which dataset do the examples use?

Eight weekly temperature and vibration readings from three machines, plus a small table of machine details. It has one missing value and two alarm rows, which is enough to show filtering, cleaning, grouping and joins. Paste it into a file or read it from a string:

import io
import pandas as pd

csv = """reading_id,machine,timestamp,temp_c,vibration_mm_s,status
1,M1,2026-11-02 08:00,61.5,2.1,ok
2,M2,2026-11-02 08:00,74.0,4.8,ok
3,M3,2026-11-02 08:00,,3.0,ok
4,M1,2026-11-09 08:00,63.0,2.4,ok
5,M2,2026-11-09 08:00,81.5,7.2,alarm
6,M3,2026-11-09 08:00,58.0,2.9,ok
7,M1,2026-11-16 08:00,64.5,2.2,ok
8,M2,2026-11-16 08:00,79.0,6.5,alarm
"""
df = pd.read_csv(io.StringIO(csv), parse_dates=["timestamp"])

machines = pd.DataFrame({"machine": ["M1", "M2", "M4"],
                         "line": ["Press shop", "Press shop", "Paint shop"],
                         "rated_temp_c": [70, 75, 60]})

How do you read and write data in pandas?

Use a pd.read_* function to load data into a DataFrame and the matching df.to_* method to save it. CSV and Excel cover most engineering work; Parquet is the better choice for large files because it keeps column types and compresses well. Excel needs the openpyxl package, and Parquet needs PyArrow.

CommandWhat it does
pd.read_csv("f.csv", parse_dates=["timestamp"])Read a CSV, parsing a date column
pd.read_csv("f.csv", engine="pyarrow")Multithreaded reader for big files (needs PyArrow)
pd.read_excel("f.xlsx", sheet_name="Log")Read one Excel sheet
pd.read_parquet("f.parquet")Read Parquet, types kept
pd.read_sql(query, conn)Run a SQL query into a DataFrame
pd.read_json("f.json")Read JSON
df.to_csv("out.csv", index=False)Write CSV without the index column
df.to_excel("out.xlsx", index=False)Write Excel
df.to_parquet("out.parquet")Write Parquet

How do you inspect a DataFrame?

Start with df.shape, df.dtypes (or df.info()), df.head() and df.isna().sum(); then df.describe() for summary statistics. On the sample, df.shape is (8, 6), and df.isna().sum() shows one missing value in temp_c.

CommandOutput on the sample
df.shape(8, 6): 8 rows, 6 columns
df.dtypesmachine and status are str; timestamp is datetime64[us]; temp_c is float64
df["temp_c"].count()7 (counts non-missing values only)
df["temp_c"].mean()68.79 (the missing value is skipped)
df["status"].value_counts()ok 6, alarm 2
df.nunique()Distinct values per column
df.memory_usage(deep=True)Bytes per column, strings counted fully

The describe() output for the two measurements:

df[["temp_c", "vibration_mm_s"]].describe().round(2)

       temp_c  vibration_mm_s
count    7.00            8.00
mean    68.79            3.89
std      9.26            2.02
min     58.00            2.10
25%     62.25            2.35
50%     64.50            2.95
75%     76.50            5.22
max     81.50            7.20

Two details in that output are pandas 3 behaviour worth knowing. Dates parsed from text now get microsecond resolution (datetime64[us]) instead of nanoseconds, so converting them to integers gives numbers 1,000 times smaller than in pandas 2. And string columns report str.

What is the difference between loc and iloc?

loc selects by label and iloc by integer position. The trap is slicing: loc includes the stop label, while iloc stops before the stop position, like a Python list. On the sample, df.loc[1:3] returns 3 rows and df.iloc[1:3] returns 2.

Eight DataFrame rows with index 0 to 7. df.loc[1:3] highlights rows 1, 2 and 3; df.iloc[1:3] highlights rows 1 and 2 only.
Same DataFrame, same numbers in the brackets, different rows. Output checked by the script in the run folder. Skill-Lync Engineering Desk.
CommandReturns
df["temp_c"]One column as a Series
df[["machine", "temp_c"]]Several columns as a DataFrame
df.loc[1:3, "machine"]Rows labelled 1 to 3 (inclusive): M2, M3, M1
df.iloc[1:3, 1]Positions 1 and 2 of column 1: M2, M3
df.iloc[0, 0]First cell
df.at[4, "temp_c"]One value by label (fast): 81.5
df.set_index("timestamp").loc["2026-11-09"]All rows on one date

How do you filter rows in pandas?

Build a Boolean mask and index with it. Combine conditions with & (and), | (or) and ~ (not), with each condition in brackets, because Python's and and or do not work element by element. df.query() does the same with a string and is easier to read for long conditions.

hot = df[(df["temp_c"] > 70) & (df["status"] == "alarm")]
hot[["reading_id", "machine", "temp_c", "vibration_mm_s"]]

   reading_id machine  temp_c  vibration_mm_s
4           5      M2    81.5             7.2
7           8      M2    79.0             6.5

df.query("vibration_mm_s >= 4.5")["reading_id"].tolist()   # [2, 5, 8]
CommandKeeps rows where
df[df["machine"].isin(["M1", "M3"])]machine is M1 or M3
df[df["temp_c"].between(60, 70)]60 ≤ temp ≤ 70 (inclusive)
df[df["status"].str.contains("al")]text contains "al"
df[~df["temp_c"].isna()]temperature is present
df.nlargest(3, "vibration_mm_s")the 3 highest vibrations
df.sort_values(["machine", "temp_c"], ascending=[True, False])(sorts, does not filter)

How do you handle missing values in pandas?

Find them with df.isna().sum(), then either drop rows with dropna() or fill them with fillna(). Filling with a group's own mean is usually better than the overall mean: the missing M3 reading below becomes 58.0, M3's mean, not 68.79, which is pulled up by the hotter M2.

df["temp_filled"] = df["temp_c"].fillna(
    df.groupby("machine")["temp_c"].transform("mean"))
df.loc[2, "temp_filled"]     # 58.0
CommandWhat it does
df.dropna()Drop rows with any missing value
df.dropna(subset=["temp_c"])Drop rows missing a temperature only
df.dropna(thresh=5)Keep rows with at least 5 non-missing values
df["temp_c"].fillna(0)Replace missing with a constant
df["temp_c"].ffill()Carry the last valid value forward (sensor logs)
df["temp_c"].interpolate()Linear fill between neighbours
df.drop_duplicates(subset=["machine", "timestamp"])Remove repeated readings

How do you add or change columns?

Assign a new column directly, or use assign() to add several in one chain. To change values in selected rows, use df.loc[mask, "col"] = value; in pandas 3 this is the only form that works. Use map to look up values from a dict, astype to change type and rename to rename.

rated = {"M1": 70, "M2": 75}
df = df.assign(over_rated=lambda d: d["temp_c"] > d["machine"].map(rated))
df.loc[df["over_rated"], "reading_id"].tolist()     # [5, 8]

df.loc[df["machine"] == "M2", "status"] = "check"  # works

# pandas 3: no effect, only a ChainedAssignmentError warning
df["temp_c"][df["machine"] == "M2"] = 0

M3 is not in the rated dict, so map gives NaN for its rows and the comparison is False: no false alarms, but no check either. Handle missing keys deliberately.

CommandWhat it does
df["temp_f"] = df["temp_c"] * 9 / 5 + 32New column from arithmetic
df.rename(columns={"temp_c": "temperature_c"})Rename a column
df["machine"].astype("category")Store repeated text compactly
df["status"].replace({"ok": "OK"})Replace values
np.where(df["vibration_mm_s"] > 4.5, "high", "normal")If-else on a column (needs import numpy as np)
df[["temp_c"]].map(round)Apply a function to every cell (was applymap)
df.drop(columns=["temp_f"])Delete a column

How do you group and aggregate in pandas?

Use groupby with named aggregation: each keyword becomes an output column, and its value is a (column, function) pair. It reads clearly and avoids the multi-level column names you get from passing a dict of lists.

df.groupby("machine").agg(
    readings=("reading_id", "count"),
    mean_temp=("temp_c", "mean"),
    max_vib=("vibration_mm_s", "max"),
    alarms=("status", lambda s: (s == "alarm").sum()),
)

         readings  mean_temp  max_vib  alarms
machine
M1              3      63.00      2.4       0
M2              3      78.17      7.2       2
M3              2      58.00      3.0       0

M2's mean is °C, and both alarms are on M2. M3's mean uses only its one valid reading (the other is missing), so it has the least evidence behind it.

CommandWhat it does
df.groupby("machine")["temp_c"].mean()One statistic per group
df.groupby("machine")["temp_c"].transform("mean")Group statistic broadcast back to every row
df.groupby(["machine", "status"]).size()Row counts for each combination
df.groupby("machine").filter(lambda g: len(g) >= 3)Keep only groups with 3+ rows
df.groupby("machine", as_index=False).agg(...)Keep the key as a normal column

What is the difference between merge, join and concat?

pd.merge joins two tables on key columns, like SQL; df.join is a shortcut that joins on the index; pd.concat stacks tables on top of each other or side by side without matching keys. The how argument decides which unmatched rows survive a merge.

Bar chart of rows returned by pd.merge of 8 readings with 3 machines: inner 6, left 8, outer 9, left_anti 2, right_anti 1, coloured by matched rows, left-only M3 rows and right-only M4.
Rows returned by each join type on the sample. The anti joins (left_anti, right_anti) are new in pandas 3.0. Counts checked by the script in the run folder.
pd.merge(df, machines, on="machine", how="left")    # 8 rows
pd.merge(df, machines, on="machine", how="outer",
         indicator=True)["_merge"].value_counts()
# both 6, left_only 2, right_only 1

# 2 rows: the M3 readings, which have no machine record
pd.merge(df, machines, on="machine", how="left_anti")
pd.merge(df, machines, on="machine", validate="one_to_one")
# MergeError: Merge keys are not unique in left dataset

validate is the most underused argument in pandas. Here it catches that one machine has many readings: the right check is validate="many_to_one", which passes. A wrong key that silently multiplies rows is one of the most common bugs in data pipelines.

CommandWhat it does
pd.concat([df_a, df_b], ignore_index=True)Stack rows (replaces df.append)
pd.concat([df_a, df_b], axis=1)Place columns side by side
pd.merge(a, b, left_on="id", right_on="machine_id")Join on differently named keys
pd.merge(a, b, how="cross")Every combination of rows
a.join(b, how="left")Join on the index

How do you reshape data with pivot_table and melt?

pivot_table turns long data into a wide grid (one row per machine, one column per date) and aggregates duplicates; melt does the reverse. Wide tables suit reports and plots; long tables suit groupby and most plotting libraries.

df.pivot_table(index="machine",
               columns=df["timestamp"].dt.strftime("%d %b"),
               values="temp_c")

timestamp  02 Nov  09 Nov  16 Nov
machine
M1           61.5    63.0    64.5
M2           74.0    81.5    79.0
M3            NaN    58.0     NaN

wide.reset_index().melt(id_vars="machine", var_name="date", value_name="temp_c")

M3's 16 Nov cell is NaN because M3 has no reading that week, not because a value was lost: the pivot makes gaps in the data visible at a glance.

How do you resample time series in pandas?

Set the timestamp as the index, then call resample with a frequency alias and an aggregation. In pandas 3, month end is "ME", quarter end "QE", year end "YE" and hour "h"; the old "M" now raises ValueError: Invalid frequency: M.

ts = df.set_index("timestamp")["temp_c"]
ts.resample("ME").mean()        # 2026-11-30    68.79
ts.resample("W").max()          # weekly maximum
ts.rolling(3, min_periods=2).mean()   # 3-reading moving average
ts.diff()                       # change from the previous reading
ts.shift(1)                     # previous reading on each row

What changed in pandas 3.0, and which old commands break?

pandas 3.0.0 (21 January 2026) made Copy-on-Write permanent, switched text to a dedicated str type and removed several long-deprecated APIs. If code from an older cheat sheet fails or silently does nothing, it is usually one of these.

Old codeIn pandas 3Use instead
df["a"][mask] = xNo effect, only a warningdf.loc[mask, "a"] = x
df.applymap(f)Removed (deprecated in 2.1)df.map(f)
df.append(row)Removed in 2.0pd.concat([df, row])
resample("M"), "Q", "Y"ValueError"ME", "QE", "YE"
"H", "T", "S"ValueError"h", "min", "s"
dtype == object checks on textText is str nowpd.api.types.is_string_dtype(s)
SettingWithCopyWarningRemoved (no longer needed)Nothing: just use .loc
pytz time zonespytz no longer requiredzoneinfo names, e.g. "Asia/Kolkata"

pandas 3.1 (22 October 2026) raised the minimum NumPy to 2.0.2. PyArrow stays optional: without it, the str type falls back to Python objects.

How do you make pandas use less memory?

Store repeated text as category, install PyArrow so str columns use its compact storage, and downcast numbers you do not need at full precision. Measure with df.memory_usage(deep=True); without deep=True, pandas does not count the size of the strings themselves.

Bar chart of memory for one million machine names with five distinct values: object 56.6 MB, str with Python storage 56.6 MB, str with PyArrow storage 15.6 MB, category 1.0 MB.
One million strings drawn from five machine names, measured with memory_usage(deep=True) on pandas 3.1.1 and PyArrow 26.0.1, 23 Nov 2026. Category stores each name once plus a 1-byte code per row. Skill-Lync Engineering Desk.

The numbers explain the advice. A category column stores 5 names once and a 1-byte code for each of the million rows, about 1 MB. PyArrow's string storage packs the characters into one buffer, about 3.6 times smaller than separate Python string objects. Category wins when values repeat; str is the right default for free text such as comments.

How should engineers practise pandas?

Use your own data: a test-rig log, a CFD monitor file, a placement spreadsheet. The commands above cover most analysis jobs, and the order is always the same: read, inspect, clean, group, join, plot. Two habits separate good analysis from fragile scripts: check row counts after every merge (or use validate), and never rely on chained assignment.

Skill-Lync's PG program in data analytics and data science and Python for mechanical engineers course use pandas on engineering datasets, and our Python project ideas give you data to practise on. Want help picking a path? Talk to a Skill-Lync counsellor.

Frequently asked questions

Is there an official pandas cheat sheet?

Yes. The pandas project publishes a two-page PDF, Pandas_Cheat_Sheet.pdf, on pandas.pydata.org, with its source in the pandas GitHub repository. It covers reshaping, subsetting, summarising, grouping and combining. It predates pandas 3, so check removed APIs such as applymap and the "M" frequency against the pandas 3.0 release notes.

What is the latest version of pandas?

pandas 3.1.1, released on 4 November 2026, is the latest release on PyPI as of 23 November 2026. pandas 3.0.0 came out on 21 January 2026. The 2.x line ended with 2.3.3 in September 2025. Current pandas needs Python 3.11 or newer and NumPy 2.0.2 or newer.

What is the difference between loc and iloc in pandas?

loc selects rows and columns by their labels, and iloc by integer position from 0. Slices differ: df.loc[1:3] includes label 3 and returns three rows, while df.iloc[1:3] stops before position 3 and returns two. Use loc for named columns and conditions, iloc for positions.

Why does my pandas assignment not change the DataFrame?

You are probably using chained assignment, such as df["col"][df["x"] > 0] = 1. Since pandas 3.0, Copy-on-Write is always on, so the first indexing step returns a copy and the assignment changes only that copy. pandas warns with ChainedAssignmentError. Write df.loc[df["x"] > 0, "col"] = 1 instead.

Do I need PyArrow for pandas 3?

No, PyArrow is optional. Without it, pandas 3 still uses the new str type for text but stores the strings as Python objects. With it, string columns use PyArrow's compact storage: in our test, one million short strings took 15.6 MB instead of 56.6 MB. PyArrow is also needed for Parquet files and engine="pyarrow".

Sources and further reading

Want this on your résumé?

Talk to a counsellor.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.