--- numeric ---
Data Manipulation
Section titled “Data Manipulation”Pandas
Section titled “Pandas”Casting
Section titled “Casting”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() firstdf['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 → NaNdf['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 detectiondf['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d") # explicit: faster + saferdf['date'] = pd.to_datetime(df['date'], dayfirst=True) # DD/MM/YYYY inputdf['date'] = pd.to_datetime(df['date'], errors='coerce') # bad values → NaTdf['date'] = pd.to_datetime(df['ts'], utc=True) # timezone-awareGotchas:
.astype(int)truncates instead of rounding —.round()first if you need rounding.- Missing datetimes become
NaT, notNaN. - Use the
.dtaccessor for components:df['date'].dt.year,.dt.month,.dt.dayofweek(Monday=0),.dt.day. dayfirst=Truematters forDD/MM/YYYYdata — otherwise pandas may misread it as USMM/DD/YYYY.- Timezone: never treat exchange/UTC timestamps as timezone-naive and assume they’re local — a classic quant-trading footgun.
Filtering
Section titled “Filtering”.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 columnsdf[df["strategy"] == "Strategy_A"] # all columnsdf.loc[df["strategy"] == "Strategy_A", "pnl"] # single columndf.loc[df["strategy"] == "Strategy_A", ["pnl", "currency"]] # multiple columns
# multiple conditions: use & (and) / | (or), wrap each in parenthesesdf[(df["strategy"] == "Strategy_A") & (df["pnl"] > 0)]df[(df["strategy"] == "Strategy_A") | (df["strategy"] == "Strategy_B")]
# membership: .isin() and ~isin() for NOT INdf[df["strategy"].isin(["Strategy_A", "Strategy_B"])]df[~df["strategy"].isin(["Strategy_A"])]
# string .str methodsdf[df["currency"].str.contains("USD")]df[df["strategy"].str.startswith("Strategy")]
# missing valuesdf[df["pnl"].isna()] # rows with NaNdf[df["pnl"].notna()] # rows without NaN
# numeric rangedf[df["pnl"].between(-100, 100)]
# .query() — readable string syntax for complex filtersdf.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 filterIndexing
Section titled “Indexing”.loc uses row/column labels (names); .iloc uses integer positions (0 to length-1).
# .loc — label-baseddf.loc[0] # single row by labeldf.loc[0:5] # slice — INCLUSIVE of label 5df.loc["Strategy_A"] # row by index namedf.loc[df["pnl"] > 0] # boolean maskdf.loc[0:5, "pnl"] # rows + one column
# .iloc — position-baseddf.iloc[0] # first rowdf.iloc[-1] # last rowdf.iloc[0:5] # first 5 rows — EXCLUSIVE of position 5df.iloc[0:5, 2] # first 5 rows, column index 2df.iloc[:, 0] # all rows, first column
# .at / .iat — fast scalar accessdf.at[0, "pnl"] # by label + column namedf.iat[0, 2] # by integer position (fastest)
# set/reset index to move data between columns and the indexdf.set_index("strategy").loc["Strategy_A"] # look up by that indexdf.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 currencymulti_currency = ( df.groupby("strategy")["currency"] .nunique() .loc[lambda x: x > 1])
ortotal = ( 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).
GroupBy
Section titled “GroupBy”Grouping returns a temporary GroupBy object — you must apply an aggregation to get data back out.
# single aggregation on one columndf.groupby("strategy")["pnl"].sum()
# multiple aggregations → DataFramedf.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 functiondf.groupby("strategy").apply(lambda g: g["pnl"].sum() / g["size"].sum())
# percentilesdf.groupby("strategy")["size"].quantile([0.1, 0.5, 0.9])
# groupby multiple keys → MultiIndexdf.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=Falsekeeps 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).
Time series
Section titled “Time series”# datetime must be the index to use .resample()df = df.set_index("timestamp")
# resample to bar frequencydf.resample("1min")["price"].agg(["open", "high", "low", "close"]) # OHLCdf.resample("5min")["size"].sum() # volume barsdf.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 enddf.resample("5min", label="right", closed="right")["price"].agg(["open", "high", "low", "close"])
# reindex to a regular grid, then forward-fill last observed valuedf.resample("5min").last().ffill() # last() ≠ ffill(): last() is per-bucket closeNotes:
- 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,
resamplebuckets by time;.diff()on timestamps gives inter-arrival gaps.
Merging
Section titled “Merging”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 rowspd.merge(df1, df2, on="symbol", how="inner") # same key name in bothpd.merge(df1, df2, left_on="sym", right_on="symbol", how="left") # different namespd.merge(df1, df2, on=["symbol", "date"], how="outer") # composite key
# suffix columns that exist in both framespd.merge(df1, df2, on="symbol", suffixes=("_left", "_right"))
# index-based joindf1.join(df2, on="symbol") # join df2 on its index or a columndf1.set_index("symbol").join(df2.set_index("symbol"))Notes:
howoptions: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.
Vectorization
Section titled “Vectorization”# vectorized column operation — operates on the whole Series at oncenotional = trades["price"] * trades["size"]
# equivalent row-by-row approaches — all slower:# (a) apply — calls a Python function per rowtrades.apply(lambda r: r["price"] * r["size"], axis=1)# (b) itertuplestotal = 0for row in trades.itertuples(): total += row.price * row.size# (c) iterrows — builds a whole new Series per row (slowest)total = 0for _, row in trades.iterrows(): total += row["price"] * row["size"]Rule of thumb for iteration choices: vectorize → itertuples → apply → iterrows (last resort).
Pivot Table
Section titled “Pivot Table”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 rowscolumns— which column’s unique values become column headersvalues— 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 zoobar A B C A B Cfooone 1 2 3 x y ztwo 4 5 6 q w tdf.pivotrequires unique index/column combinations — no duplicates. A duplicate key raises an error.df.pivot_tableis the generalised version: it takes anaggfunc(default'mean') instead ofvalues, so it aggregates duplicates (e.g.sum,mean,count) and supportsmargins(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 E0 foo one small 1 21 foo one large 2 42 foo one large 2 53 foo two small 3 54 foo two small 3 65 bar one large 4 66 bar one small 5 87 bar two small 6 98 bar two large 7 9
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], aggfunc={'D': "mean", 'E': "mean"})>>> table D EA Cbar large 5.500000 7.500000 small 5.500000 8.500000foo large 2.000000 4.500000 small 2.333333 4.333333Inverse: pd.melt unpivots a wide table back into long form — pivot and melt swap between wide and long layouts.
Groupby
Section titled “Groupby”Groupby.transform('sum') can be used to broadcast the function to apply to all groups