pandas for Log Analysis
A for loop and a Counter are enough for a hundred log lines. For a day of authentication events from twenty servers, questions like "which sources failed more than ten times in any five-minute window?" or "which account logged in from a new country?" are table operations: group, count, window, join. pandas does those in a few readable lines, and it is how most analysts explore logs before they write a detection rule. The library itself is taught in pandas; this lesson uses it on security data and points out where it misleads.
Definitions
- DataFrame: a table with named, typed columns. One row per event.
- Parsed timestamps:
pd.to_datetime(..., utc=True)turns text into adatetime64column you can sort, window and compare. Text timestamps sort wrongly and can't be windowed. groupby: split rows by a key (source, account), then aggregate (count, distinct count, first and last time).- Time window:
resample("5min")buckets events into fixed windows;rolling("5min")looks back five minutes from each event, so a burst that straddles a bucket boundary is not split. - Join:
mergeadds context (asset owner, known-good sources) from a second table.
A day of logins in a table
The events are synthetic, from a lab SSH gateway. Two things are hidden in them: a burst of failures from one source, and an account that succeeded from a source it has never used.
import pandas as pd
rows = [
("2026-01-15T08:01:00Z", "10.10.0.21", "alice", "ok"),
("2026-01-15T08:15:00Z", "10.10.0.22", "bob", "fail"),
("2026-01-15T08:15:20Z", "10.10.0.22", "bob", "ok"),
("2026-01-15T09:00:00Z", "10.10.0.23", "carol", "ok"),
("2026-01-15T12:30:00Z", "10.10.0.21", "alice", "ok"),
]
# 12 failures in 4 minutes, across the 10:05 bucket boundary
for i in range(12):
rows.append((f"2026-01-15T10:{2 + i // 3:02d}:{(i % 3) * 20 + 10:02d}Z", "203.0.113.7", "admin", "fail"))
rows.append(("2026-01-15T10:07:00Z", "203.0.113.7", "carol", "ok"))
df = pd.DataFrame(rows, columns=["time", "src", "user", "result"])
df["time"] = pd.to_datetime(df["time"], utc=True)
df = df.sort_values("time").reset_index(drop=True)
print(df.dtypes.to_dict())
print("\n== top talkers")
print(df.groupby("src").agg(events=("user", "size"), fails=("result", lambda r: (r == "fail").sum()),
accounts=("user", "nunique")).sort_values("events", ascending=False))
fails = df[df["result"] == "fail"].set_index("time")
print("\n== fixed 5-minute buckets, failures per source")
buckets = fails.groupby(["src", pd.Grouper(freq="5min")]).size()
print(buckets[buckets > 0])
print("\n== rolling 5-minute window, peak per source")
fails = fails.assign(one=1)
peak = fails.groupby("src")["one"].rolling("5min").sum().groupby(level=0).max()
print(peak.astype(int)){'time': datetime64[ns, UTC], 'src': dtype('O'), 'user': dtype('O'), 'result': dtype('O')}
== top talkers
events fails accounts
src
203.0.113.7 13 12 2
10.10.0.21 2 0 1
10.10.0.22 2 1 1
10.10.0.23 1 0 1
== fixed 5-minute buckets, failures per source
src time
10.10.0.22 2026-01-15 08:15:00+00:00 1
203.0.113.7 2026-01-15 10:00:00+00:00 9
2026-01-15 10:05:00+00:00 3
dtype: int64
== rolling 5-minute window, peak per source
src
10.10.0.22 1
203.0.113.7 12
Name: one, dtype: int32
The fixed buckets split the burst into two smaller counts, so a rule "more than 10 in a 5-minute bucket" would never fire. The rolling window looks back five minutes from each failure and sees all twelve. Brute-force detections in SIEMs use sliding windows for exactly this reason; Brute Force and Password Spraying shows the attack side.
New source for an account
A success from a source the account has never used before is worth a look, especially right after a burst of failures from the same source. A merge against each account's history answers it:
import pandas as pd
df = pd.DataFrame([
("2026-01-14T09:00:00Z", "10.10.0.23", "carol", "ok"),
("2026-01-14T17:00:00Z", "10.10.0.23", "carol", "ok"),
("2026-01-14T09:10:00Z", "10.10.0.21", "alice", "ok"),
("2026-01-15T09:00:00Z", "10.10.0.23", "carol", "ok"),
("2026-01-15T10:05:00Z", "203.0.113.7", "admin", "fail"),
("2026-01-15T10:07:00Z", "203.0.113.7", "carol", "ok"),
("2026-01-15T12:30:00Z", "10.10.0.21", "alice", "ok"),
], columns=["time", "src", "user", "result"])
df["time"] = pd.to_datetime(df["time"], utc=True)
cutoff = pd.Timestamp("2026-01-15", tz="UTC")
history = df[df["time"] < cutoff].groupby("user")["src"].agg(set).rename("known")
today = df[(df["time"] >= cutoff) & (df["result"] == "ok")].join(history, on="user")
today["new_source"] = [s not in k if isinstance(k, set) else True for s, k in zip(today["src"], today["known"])]
print(today[["time", "user", "src", "new_source"]].to_string(index=False))
failed_srcs = set(df.loc[df["result"] == "fail", "src"])
alerts = today[today["new_source"] & today["src"].isin(failed_srcs)]
for _, a in alerts.iterrows():
print(f"ALERT {a['user']} logged in from new source {a['src']}, which also had failures") time user src new_source
2026-01-15 09:00:00+00:00 carol 10.10.0.23 False
2026-01-15 10:07:00+00:00 carol 203.0.113.7 True
2026-01-15 12:30:00+00:00 alice 10.10.0.21 False
ALERT carol logged in from new source 203.0.113.7, which also had failures
How pandas analyses go wrong (detection)
- Check the dtypes first. A
timecolumn of typeobjectis text: sorting is alphabetical and windows fail. - Count rows before and after every filter and join. An inner join silently drops events whose key is missing from the context table; a many-to-many join multiplies rows.
- Look at the edges of windows: compare fixed and rolling counts, as above. A burst that lands across a boundary is the classic miss.
- Watch the time zone. Mixing local times and UTC shifts events by hours and breaks "before/after" logic.
How to make it reliable (fix)
- Parse at load time with
utc=Trueand an explicitformatwhen you know it; reject rows that fail (errors="coerce", then count theNaTs). - Prefer
rollingwindows for burst detection and say the window length in the report. - Use left joins and check for
NaNafter them, as the example does withisinstance(k, set)for accounts that have no history. - Keep the raw line in a column so every alert can be traced back to its evidence.
- When the exploration works, turn it into a rule in the SIEM or a tested script (the log analyser project), with the same window and threshold.
Pitfalls
- Memory. pandas loads everything; a week of verbose logs may not fit. Filter early (
usecols,chunksizeinread_csv), or use a SIEM. - Spreadsheet injection. Exporting fields such as
=HYPERLINK(...)to CSV for a colleague to open in Excel can execute formulas. Prefix cells that start with= + - @with a'when exporting attacker-controlled text. - Lambda aggregations are slow on millions of rows;
(df.result == "fail").groupby(df.src).sum()is vectorised.
Practice
1. Add a column minute and count failures per source per minute. What is the peak for 203.0.113.7?
fails.groupby(["src", fails.index.floor("min")]).size() — the burst puts 3 failures in each of the minutes 10:02 to 10:05, so the peak is 3. Per-minute counts hide bursts even more than 5-minute buckets.
2. Why does the second example need a left join?
A brand-new account has no history. An inner join would drop them, and a first-ever login, which is the most suspicious, would vanish from the report. With a left join their known is NaN and they count as a new source.
3. Which column would you add to tell "new source" from "new source, in a country never seen for this organisation"?
A geolocation or network-owner column joined from an IP-to-ASN/country table (an offline database in a real SOC), then a second history: sources' countries per account and for the whole organisation.
Test yourself
Why did the fixed 5-minute buckets miss the burst that the rolling window caught?
- resample drops failures
- The burst straddled a bucket boundary, so each bucket saw only part of it
- Rolling windows count twice
- The timestamps were text
A timestamp column has dtype object. What is the problem?
- Nothing
- It is text, so sorting is alphabetical and time windows don't work
- It uses too much memory
- It is in UTC
Which join keeps accounts that have no login history?
- inner
- left (from today's events)
- cross
- none
Why prefix CSV cells starting with = with an apostrophe when exporting attacker-controlled fields?
- To save space
- To stop spreadsheet programs from evaluating them as formulas (CSV injection)
- Because pandas requires it
- To sort them first