Data & Backend

Python Data Analysis & Pandas Cheat Sheet

Quick reference for Python data workflows: NumPy vectorization & boolean masks, statistics & IQR outliers, Pandas loc/iloc, cleaning, groupby/merge/pivot_table, read_sql, time-series resampling, Matplotlib/Seaborn, and BeautifulSoup.

1 min readUpdated 2026-11-30

NumPy Vectorization & Boolean Masks

python
import numpy as np

prices = np.array([19.99, 45.0, 120.0])
with_tax = np.round(prices * 1.10, 2)
mid = prices[(prices >= 15) & (prices <= 60)]   # Use & / | with parentheses!

Statistics & IQR Outliers

python
import statistics

med = statistics.median(values)
q1, _, q3 = statistics.quantiles(values, n=4)
iqr = q3 - q1
outliers = [x for x in values if x < q1 - 1.5 * iqr or x > q3 + 1.5 * iqr]

Pandas Selection, Cleaning & Joins

python
import pandas as pd

# Safe row+col selection
active = df.loc[df["status"] == "paid", ["customer", "amount"]]

# Clean currency strings without crashing
df["amount"] = (
    df["amount"].astype(str).str.replace(r"[$,]", "", regex=True)
    .pipe(pd.to_numeric, errors="coerce")
)
df = df.drop_duplicates(subset=["order_id"], keep="first")

# GroupBy + Merge validation
summary = df.groupby("category", as_index=False).agg(
    revenue=("amount", "sum"), orders=("order_id", "count")
)
merged = pd.merge(df, customers, on="customer_id", how="left", validate="many_to_one")

Time-Series & SQLite

python
df["ordered_at"] = pd.to_datetime(df["ordered_at"])
monthly = df.sort_values("ordered_at").set_index("ordered_at")["amount"].resample("ME").sum()
ma_7d = monthly.rolling(window=7, min_periods=1).mean()

with sqlite3.connect("academy.db") as conn:
    rows = pd.read_sql_query("SELECT * FROM orders WHERE amount >= ?", conn, params=(50,))

Matplotlib (fig, ax) & BeautifulSoup

python
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(summary["category"], summary["revenue"])
ax.set_ylim(bottom=0)
fig.tight_layout()
fig.savefig("revenue.png", dpi=150)

soup = BeautifulSoup(html_text, "html.parser")
titles = [el.get_text(strip=True) for el in soup.select("h2.title")]