Skip to content

--- numeric ---

float() only works on a single value — not a whole column. For a Series, use .astype(...) or pd.to_numeric / pd.to_datetime.

# --- numeric ---
df['price'] = df['price'].replace("$", "").replace(",", "").astype(float)
df['col'] = df['col'].astype(int) # truncates! use .round() first
df['col'] = df['col'].astype(str)
df['col'] = df['col'].astype("category") # categorical (memory-efficient)
df['col'] = pd.to_numeric(df['col'], errors='coerce') # bad values → NaN
df['col'] = pd.to_numeric(df['col'], downcast='float') # float64 → float32
# --- single scalar ---
price = float("$1,234.56".replace("$", "").replace(",", ""))
# --- datetime (prefer pd.to_datetime over .astype("datetime64")) ---
df['date'] = pd.to_datetime(df['date']) # auto-format detection
df['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d") # explicit: faster + safer
df['date'] = pd.to_datetime(df['date'], dayfirst=True) # DD/MM/YYYY input
df['date'] = pd.to_datetime(df['date'], errors='coerce') # bad values → NaT
df['date'] = pd.to_datetime(df['ts'], utc=True) # timezone-aware

Gotchas:

  • .astype(int) truncates instead of rounding — .round() first if you need rounding.
  • Missing datetimes become NaT, not NaN.
  • Use the .dt accessor for components: df['date'].dt.year, .dt.month, .dt.dayofweek (Monday=0), .dt.day.
  • dayfirst=True matters for DD/MM/YYYY data — otherwise pandas may misread it as US MM/DD/YYYY.
  • Timezone: never treat exchange/UTC timestamps as timezone-naive and assume they’re local — a classic quant-trading footgun.

.loc[row_indexer, column_indexer] - access groups of rows and columns by labels or boolean masks. slices are inclusive of end label.

.iloc[row_index, column_indexer] - access by integer position, slices are exclusive of end position. can also take in boolean function. e.g. lambda x: x.index % 2 == 0

Use .query() for complex filters.

# filter for rows where strategy is "Strategy_A", then select columns
df[df["strategy"] == "Strategy_A"] # all columns
df.loc[df["strategy"] == "Strategy_A", "pnl"] # single column
df.loc[df["strategy"] == "Strategy_A", ["pnl", "currency"]] # multiple columns
# multiple conditions: use & (and) / | (or), wrap each in parentheses
df[(df["strategy"] == "Strategy_A") & (df["pnl"] > 0)]
df[(df["strategy"] == "Strategy_A") | (df["strategy"] == "Strategy_B")]
# membership: .isin() and ~isin() for NOT IN
df[df["strategy"].isin(["Strategy_A", "Strategy_B"])]
df[~df["strategy"].isin(["Strategy_A"])]
# string .str methods
df[df["currency"].str.contains("USD")]
df[df["strategy"].str.startswith("Strategy")]
# missing values
df[df["pnl"].isna()] # rows with NaN
df[df["pnl"].notna()] # rows without NaN
# numeric range
df[df["pnl"].between(-100, 100)]
# .query() — readable string syntax for complex filters
df.query("strategy == 'Strategy_A' and pnl > 0")
df.query("strategy in ['Strategy_A', 'Strategy_B']")
# .eval() builds a mask without materialising intermediate Python objects (fast on big frames)
mask = df.eval("a > 0.5 and b < 0.3")
df[mask] # apply the eval mask as a filter

.loc uses row/column labels (names); .iloc uses integer positions (0 to length-1).

# .loc — label-based
df.loc[0] # single row by label
df.loc[0:5] # slice — INCLUSIVE of label 5
df.loc["Strategy_A"] # row by index name
df.loc[df["pnl"] > 0] # boolean mask
df.loc[0:5, "pnl"] # rows + one column
# .iloc — position-based
df.iloc[0] # first row
df.iloc[-1] # last row
df.iloc[0:5] # first 5 rows — EXCLUSIVE of position 5
df.iloc[0:5, 2] # first 5 rows, column index 2
df.iloc[:, 0] # all rows, first column
# .at / .iat — fast scalar access
df.at[0, "pnl"] # by label + column name
df.iat[0, 2] # by integer position (fastest)
# set/reset index to move data between columns and the index
df.set_index("strategy").loc["Strategy_A"] # look up by that index
df.reset_index() # index back to a column
# multiple index levels (MultiIndex)
df.set_index(["strategy", "currency"])
df.loc[("Strategy_A", "USD")] # pass a tuple of level values
# group by strategy, count unique currencies, and filter for strategies with more than 1 currency
multi_currency = (
df.groupby("strategy")["currency"]
.nunique()
.loc[lambda x: x > 1]
)
or
total = (
df.groupby("strategy")
.agg(total=("pnl", "sum"))
.loc[lambda x: x["total"] > 1000] # x is the agg'd DataFrame
)

Key gotcha: slicing is inclusive for .loc (df.loc[0:5] includes label 5) but exclusive for .iloc (df.iloc[0:5] gives positions 0-4).

Grouping returns a temporary GroupBy object — you must apply an aggregation to get data back out.

# single aggregation on one column
df.groupby("strategy")["pnl"].sum()
# multiple aggregations → DataFrame
df.groupby("strategy")["pnl"].agg(["sum", "mean", "count", "std"])
# different aggs per column (named aggregation)
df.groupby("strategy").agg(
total_pnl=("pnl", "sum"),
avg_size=("size", "mean"),
)
# custom function
df.groupby("strategy").apply(lambda g: g["pnl"].sum() / g["size"].sum())
# percentiles
df.groupby("strategy")["size"].quantile([0.1, 0.5, 0.9])
# groupby multiple keys → MultiIndex
df.groupby(["strategy", "side"])["size"].agg(["min", "max", "count"])
# VWAP convention (weighted mean of price by size)
vwap = (df["price"] * df["size"]).groupby(df["symbol"]).sum() / \
df.groupby("symbol")["size"].sum()

Notes:

  • Use .agg() with a dict/list for different aggregations; .apply() is slower and less predictable.
  • as_index=False keeps the group key as a column instead of the index (or use .reset_index()).
  • .transform() broadcasts the result back to the original row count (e.g. subtract group mean from each row).
# datetime must be the index to use .resample()
df = df.set_index("timestamp")
# resample to bar frequency
df.resample("1min")["price"].agg(["open", "high", "low", "close"]) # OHLC
df.resample("5min")["size"].sum() # volume bars
df.resample("30min").apply(lambda g: (g["price"] * g["size"]).sum() / g["size"].sum())
# last() / first() — the last/first VALUE inside each bucket (bar close/open)
df.resample("5min")["price"].last()
df.resample("5min")["price"].first()
df.resample("5min")["price"].agg(["first", "max", "min", "last"]) # OHLC explicitly
# label= / closed= control which bucket boundary carries the label:
# default label="left", closed="left" → bucket = [t, t+5min), labelled by start
# label="right", closed="right" → bucket = (t-5min, t], labelled by end
df.resample("5min", label="right", closed="right")["price"].agg(["open", "high", "low", "close"])
# reindex to a regular grid, then forward-fill last observed value
df.resample("5min").last().ffill() # last() ≠ ffill(): last() is per-bucket close

Notes:

  • Resample frequencies: "1min", "5min", "1H", "30min", "1D", "1W", "Q".
  • rolling(window).apply(fn) is slow — prefer built-ins (mean/sum/std/quantile) whenever possible.
  • For irregular timestamps, resample buckets by time; .diff() on timestamps gives inter-arrival gaps.

pd.merge joins two DataFrames on a key (SQL-style); how= controls which rows survive.

# inner: only matching keys (default), outer: all, left/right: keep one side's rows
pd.merge(df1, df2, on="symbol", how="inner") # same key name in both
pd.merge(df1, df2, left_on="sym", right_on="symbol", how="left") # different names
pd.merge(df1, df2, on=["symbol", "date"], how="outer") # composite key
# suffix columns that exist in both frames
pd.merge(df1, df2, on="symbol", suffixes=("_left", "_right"))
# index-based join
df1.join(df2, on="symbol") # join df2 on its index or a column
df1.set_index("symbol").join(df2.set_index("symbol"))

Notes:

  • how options: inner (default), outer, left, right — mirror SQL joins.
  • Watch for duplicated keys → a fan-out / cartesian blow-up; check validate="one_to_one" to catch it.
  • One-to-many: pd.merge(df_ones, df_many, on="key").

merge_asof (time-aware merge) — use when there’s no exact key match and you want the most recent preceding row, e.g. attaching the prevailing mid-price to each trade.

# for each trade, attach the most recent order-book snapshot mid (per symbol).
# BOTH must be sorted by the time key; direction='backward' = "at or before t".
trades_sorted = trades.sort_values("timestamp")
book_sorted = book.sort_values("timestamp")
merged = pd.merge_asof(
trades_sorted,
book_sorted[["timestamp", "mid"]],
on="timestamp",
by="symbol", # match per group (symbol must be in both)
direction="backward", # most recent snapshot ≤ trade time (default)
)

Key options:

  • direction="backward" (default) — most recent ≤ t; "forward" — next ≥ t; "nearest" — closest.
  • by= groups the merge (e.g. per symbol/currency). BOTH frames must be sorted by the time key and by the group keys.
  • tolerance= sets a max time difference (e.g. timedelta(seconds=5)) — unmatched rows get NaN.
  • Classic uses: arrival-price benchmark, VWAP benchmark, spread at trade time.
# vectorized column operation — operates on the whole Series at once
notional = trades["price"] * trades["size"]
# equivalent row-by-row approaches — all slower:
# (a) apply — calls a Python function per row
trades.apply(lambda r: r["price"] * r["size"], axis=1)
# (b) itertuples
total = 0
for row in trades.itertuples():
total += row.price * row.size
# (c) iterrows — builds a whole new Series per row (slowest)
total = 0
for _, row in trades.iterrows():
total += row["price"] * row["size"]

Rule of thumb for iteration choices: vectorize → itertuples → apply → iterrows (last resort).

Pivot tables reshape (“pivot”) a long table into a wide one by re-arranging values from columns into the row/column axes. You pick:

  • index — which column’s unique values become rows
  • columns — which column’s unique values become column headers
  • values — which column’s entries fill the cells

Each cell holds the value from values where the index value matches the columns value. Missing combinations become NaN.

>>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
baz zoo
bar A B C A B C
foo
one 1 2 3 x y z
two 4 5 6 q w t
  • df.pivot requires unique index/column combinations — no duplicates. A duplicate key raises an error.
  • df.pivot_table is the generalised version: it takes an aggfunc (default 'mean') instead of values, so it aggregates duplicates (e.g. sum, mean, count) and supports margins (row/column totals) and multi-level indices/columns. Use it whenever the data could collide.
df.pivot_table(index='foo', columns='bar', values='baz', aggfunc='sum')
>>> df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], aggfunc={'D': "mean", 'E': "mean"})
>>> table
D E
A C
bar large 5.500000 7.500000
small 5.500000 8.500000
foo large 2.000000 4.500000
small 2.333333 4.333333

Inverse: pd.melt unpivots a wide table back into long form — pivot and melt swap between wide and long layouts.

Groupby.transform('sum') can be used to broadcast the function to apply to all groups