Skip to content

Python Cheat Sheet for Analytics

Quick reference for Python patterns used in data analysis.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
from collections import defaultdict, Counter

Data Types

# Numbers
int_val = 42
float_val = 3.14
# Arithmetic: + - * / // (integer div) % (modulo) ** (power)
print(f{float_val:,.2f}")    # formatted string

# Strings
s = "Hello, World!"
s.lower() / s.upper() / s.strip() / s.split(",")
s.replace("Hello", "Hi") / s.startswith("H") / s.endswith("!")
f"Revenue: £{42000:,}"        # f-string formatting

# Lists
lst = [1, 2, 3, 4, 5]
lst[0]        # first element
lst[-1]       # last element
lst[1:4]      # slice: elements 1, 2, 3
lst.append(6) / lst.extend([7, 8]) / lst.sort()

# Dictionaries
d = {"key": "value", "count": 5}
d["key"]                    # access
d.get("missing", "default") # safe access
d.items() / d.keys() / d.values()

# Sets
s = {1, 2, 3}
s1 & s2   # intersection
s1 | s2   # union
s1 - s2   # difference

Control Flow

# Conditional
if x > 100:
    label = "High"
elif x > 50:
    label = "Medium"
else:
    label = "Low"

# Ternary
label = "High" if x > 100 else "Low"

# For loop
for i, item in enumerate(items, start=1):
    print(f"{i}. {item}")

for key, val in d.items():
    print(f"{key}: {val}")

for a, b in zip(list1, list2):
    print(a, b)

# List comprehension
squares = [x**2 for x in range(10)]
filtered = [x for x in data if x > 0]

Functions

def calculate_margin(revenue, cost, decimals=2):
    """Calculate gross margin as a percentage."""
    if revenue == 0:
        return 0
    return round((revenue - cost) / revenue * 100, decimals)

# Lambda
classify = lambda x: "High" if x > 200 else "Low"

# *args and **kwargs
def summarise(*values, label="Summary"):
    print(f"{label}: mean={sum(values)/len(values):.2f}")

File Handling

from pathlib import Path
import csv

# Read CSV
with open("data.csv", "r", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    data = list(reader)   # list of dicts, all values are strings

# Write CSV
with open("output.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["id", "name", "total"])
    writer.writeheader()
    writer.writerows(rows)

# List all CSVs in a directory
csv_files = list(Path("data").glob("*.csv"))

# Safe file check
if Path("data.csv").exists():
    ...

NumPy

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
arr * 2          # vectorised: [2, 4, 6, 8, 10]
arr[arr > 2]     # boolean indexing: [3, 4, 5]

np.mean(arr) / np.median(arr) / np.std(arr, ddof=1)
np.sum(arr) / np.cumsum(arr)
np.percentile(arr, [25, 50, 75])
np.argmax(arr) / np.argmin(arr)  # index of max/min
np.log1p(arr)    # log(1+x) — handles 0s
np.clip(arr, 0, 100)  # cap values
np.where(arr > 3, "High", "Low")  # element-wise conditional

Statistical Analysis

from scipy import stats

# Descriptive
stats.describe(data)
stats.skew(data)
stats.kurtosis(data)

# Normality test
stat, p = stats.shapiro(data)

# T-tests
stats.ttest_1samp(data, popmean=100)           # one-sample
stats.ttest_ind(group_a, group_b, equal_var=False)  # two-sample (Welch)

# Correlation
r, p = stats.pearsonr(x, y)
r_s, p_s = stats.spearmanr(x, y)

# Confidence interval
ci = stats.t.interval(0.95, df=len(data)-1, loc=np.mean(data), scale=stats.sem(data))

Matplotlib Quick Reference

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 5))

ax.plot(x, y, color="#0D9488", linewidth=2, label="Revenue")
ax.bar(x, y, color="#0D9488", alpha=0.8, edgecolor="none")
ax.scatter(x, y, alpha=0.4, c="blue", s=30)
ax.hist(data, bins=30, edgecolor="white")
ax.boxplot(data, vert=True)

ax.set_title("Title")
ax.set_xlabel("X Label") / ax.set_ylabel("Y Label")
ax.legend()
ax.grid(True, alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f{x:,.0f}"))

plt.tight_layout()
plt.savefig("chart.png", dpi=150, bbox_inches="tight")
plt.show()

Data Pipeline Pattern

from collections import defaultdict

def load(filepath):
    with open(filepath, "r", newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))

def transform(records):
    return [
        {**r, "total": float(r["qty"]) * float(r["price"])}
        for r in records
        if r["status"] == "completed"
    ]

def aggregate(records):
    summary = defaultdict(lambda: {"orders": 0, "revenue": 0.0})
    for r in records:
        summary[r["category"]]["orders"] += 1
        summary[r["category"]]["revenue"] += r["total"]
    return dict(summary)

def export(summary, filepath):
    rows = [{"category": k, **v} for k, v in sorted(summary.items())]
    with open(filepath, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["category", "orders", "revenue"])
        writer.writeheader()
        writer.writerows(rows)

# Run pipeline
raw = load("orders.csv")
clean = transform(raw)
summary = aggregate(clean)
export(summary, "category_summary.csv")