Journeys and sequences
Turn an event log into the paths people take and what they do next. Read a flow diagram and a transition matrix without inventing causes.
What runs in CodeSplash
- Event sequences and journeys Verified in Python and R
You will be able to
- Prepare an event log with who, when and what
- Read common paths, a flow diagram and a transition matrix
- Say what a transition probability assumes and what it can't show
Order is the data
ReadCounts lose the order of events. Two customers can both have one purchase, one support ticket and one cancellation, yet a ticket before canceling tells a different story from a ticket afterwards.
Sequence analysisSequence analysisSummarizes ordered events per entity — common paths, what happens next and where journeys end. keeps the order. It takes an event log with one row per event and three columns: who, when and what.
Events at the same time keep their order in the data, so check for ties if your timestamps are coarse. A day-level timestamp can scramble what really happened in the morning and the afternoon.
Make a guess
PredictPredict first
Across 150 customer journeys with six kinds of events, what share follow the single most common path over the first four steps?
Make your guess between 0 and 100 % of journeys, then reveal.
Reveal
Only 13% do, out of 43 distinct paths. Most journeys don't follow the top path, and that's normal. A funnel diagram that shows one path hides the rest.
Read the flow
ExploreView data
| step | from | to | journeys |
|---|---|---|---|
| 1 | 1: visit | 2: (end) | 48 |
| 1 | 1: visit | 2: search | 153 |
| 1 | 1: visit | 2: view | 199 |
| 2 | 2: search | 3: (end) | 16 |
| 2 | 2: search | 3: cart | 11 |
| 2 | 2: search | 3: search | 9 |
| 2 | 2: search | 3: view | 117 |
| 2 | 2: view | 3: (end) | 33 |
| 2 | 2: view | 3: cart | 59 |
| 2 | 2: view | 3: search | 36 |
| 2 | 2: view | 3: view | 71 |
| 3 | 3: cart | 4: (end) | 11 |
| 3 | 3: cart | 4: checkout | 39 |
| 3 | 3: cart | 4: search | 6 |
| 3 | 3: cart | 4: view | 14 |
| 3 | 3: search | 4: (end) | 5 |
| 3 | 3: search | 4: search | 5 |
| 3 | 3: search | 4: view | 35 |
| 3 | 3: view | 4: (end) | 17 |
| 3 | 3: view | 4: cart | 71 |
| 3 | 3: view | 4: search | 31 |
| 3 | 3: view | 4: view | 69 |
Each column is a step, each band an event, and width shows how many journeys take it. Start at the left and follow the widest band. Then look for where a band splits or thins out: that's where journeys diverge or end.
The steps option sets how many events are compared, and top_events sets how many event kinds get their own band, with the others grouped as Other. With 2 steps and 3 events, the top path covers 49% of journeys over 3 paths, so a coarser view makes one path look dominant.
What happens next?
ReadThe transition matrixTransition matrixFor each event, the share of times each other event (or the end of the journey) comes next. gives, for each event, the probability of each next event, including the start and end of a journey.
It's a compact summary, but it assumes that what comes next depends only on the current event. If people who complained twice behave differently from people who complained once, the matrix can't show that.
Read the card
Read150 journeys, 896 events of 6 kinds; the most common path (visit → search → view → view) covers 13%.
- Journeys
- 150
- Mean length
- 5.973
- Top path
- 12.7%
Plots
View data
| Journeys | From | Step | To |
|---|---|---|---|
| 74 | 1: visit | 1 | 2: search |
| 22 | 1: visit | 1 | 2: support |
| 54 | 1: visit | 1 | 2: view |
| 1 | 2: search | 2 | 3: cart |
| 13 | 2: search | 2 | 3: search |
| 7 | 2: search | 2 | 3: support |
| 53 | 2: search | 2 | 3: view |
| 3 | 2: support | 2 | 3: cart |
| 3 | 2: support | 2 | 3: search |
| 2 | 2: support | 2 | 3: support |
| 14 | 2: support | 2 | 3: view |
| 18 | 2: view | 2 | 3: cart |
| 12 | 2: view | 2 | 3: search |
| 7 | 2: view | 2 | 3: support |
| 17 | 2: view | 2 | 3: view |
| 4 | 3: cart | 3 | 4: (end) |
| 11 | 3: cart | 3 | 4: checkout |
| 2 | 3: cart | 3 | 4: support |
| 5 | 3: cart | 3 | 4: view |
| 5 | 3: search | 3 | 4: (end) |
| 2 | 3: search | 3 | 4: cart |
| 6 | 3: search | 3 | 4: search |
| 2 | 3: search | 3 | 4: support |
| 13 | 3: search | 3 | 4: view |
| 3 | 3: support | 3 | 4: (end) |
| 6 | 3: support | 3 | 4: search |
| 1 | 3: support | 3 | 4: support |
| 6 | 3: support | 3 | 4: view |
| 13 | 3: view | 3 | 4: (end) |
| 21 | 3: view | 3 | 4: cart |
| 17 | 3: view | 3 | 4: search |
| 6 | 3: view | 3 | 4: support |
| 27 | 3: view | 3 | 4: view |
Most common paths (first 4 steps)
| Rank | Path | Journeys | Share |
|---|---|---|---|
| 1 | visit → search → view → view | 19 | 12.7% |
| 2 | visit → search → view → cart | 11 | 7.3% |
| 3 | visit → search → view → search | 10 | 6.7% |
| 4 | visit → search → view → (end) | 9 | 6.0% |
| 5 | visit → view → cart → checkout | 9 | 6.0% |
| 6 | visit → search → search → view | 7 | 4.7% |
| 7 | visit → view → view → search | 6 | 4.0% |
| 8 | visit → support → view → cart | 5 | 3.3% |
| 9 | visit → view → search → view | 5 | 3.3% |
| 10 | visit → view → view → cart | 5 | 3.3% |
| 11 | visit → search → view → support | 4 | 2.7% |
| 12 | visit → support → view → view | 4 | 2.7% |
| 13 | visit → view → cart → view | 4 | 2.7% |
| 14 | visit → view → view → view | 4 | 2.7% |
| 15 | visit → search → support → search | 3 | 2.0% |
| 16 | visit → search → support → view | 3 | 2.0% |
| 17 | visit → support → view → (end) | 3 | 2.0% |
| 18 | visit → view → cart → (end) | 3 | 2.0% |
| 19 | visit → view → search → search | 3 | 2.0% |
| 20 | visit → view → support → search | 3 | 2.0% |
What happens next (row → column probabilities)
| From | view | search | visit | support | cart | checkout | (end) |
|---|---|---|---|---|---|---|---|
| (start) | 0.0% | 0.0% | 100.0% | 0.0% | 0.0% | 0.0% | 0.0% |
| view | 27.8% | 16.0% | 0.0% | 12.5% | 24.0% | 0.0% | 19.8% |
| search | 55.2% | 14.2% | 0.0% | 8.7% | 3.8% | 0.0% | 18.0% |
| visit | 37.1% | 47.2% | 0.0% | 14.5% | 0.0% | 0.0% | 1.3% |
| support | 33.0% | 24.1% | 0.0% | 15.2% | 6.3% | 0.0% | 21.4% |
| cart | 22.5% | 5.6% | 0.0% | 7.9% | 0.0% | 44.9% | 19.1% |
| checkout | 22.5% | 0.0% | 22.5% | 25.0% | 0.0% | 0.0% | 30.0% |
The exact R script · R R version 4.5.1 (2025-06-13)
# Event sequences and journeys
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sequences 1.0.0 · spec fdecb4a1d706db95
# Dataset: ds1_events (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
ENTITY <- "customer"
TIME <- "minute"
EVENT <- "event"
STEPS <- 4
TOP_EVENTS <- 6
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ds1_events.parquet", col_select = unique(c(ENTITY, TIME, EVENT))))
warnings <- list()
ok <- !is.na(df[[ENTITY]]) & !is.na(df[[TIME]]) & !is.na(df[[EVENT]])
if (!all(ok)) warnings <- c(warnings, sprintf("%d rows with a missing journey, time or event were left out.", sum(!ok)))
df <- df[ok, , drop = FALSE]
journeys <- cs_ml_sequences(df[[ENTITY]], as.numeric(df[[TIME]]), df[[EVENT]])
if (!length(journeys)) stop("No complete events to analyze.")
# %% Counts
lengths <- vapply(journeys, function(j) length(j$events), numeric(1))
all_events <- unlist(lapply(journeys, function(j) j$events))
tab <- table(all_events)
cnt <- as.integer(tab); names(cnt) <- names(tab)
types <- names(cnt)[order(-cnt, names(cnt), method = "radix")]
START <- "(start)"; END <- "(end)"
pairs_ <- unlist(lapply(journeys, function(j) {
chain <- c(START, j$events, END)
paste(chain[-length(chain)], chain[-1], sep = "\u0001")
}))
trans <- table(pairs_)
trans_n <- as.integer(trans); names(trans_n) <- names(trans)
from_of <- sub("\u0001.*$", "", names(trans_n)); to_of <- sub("^.*\u0001", "", names(trans_n))
from_tot <- tapply(trans_n, from_of, sum)
tr <- function(a, b) { k <- paste(a, b, sep = "\u0001"); if (k %in% names(trans_n)) trans_n[[k]] else 0L }
path_of <- vapply(journeys, function(j) {
ev <- j$events
paste(c(utils::head(ev, STEPS), if (length(ev) < STEPS) END), collapse = " → ")
}, character(1))
ptab <- table(path_of)
pcount <- as.integer(ptab); names(pcount) <- names(ptab)
ranked <- names(pcount)[order(-pcount, names(pcount), method = "radix")]
n <- length(journeys)
repeat_n <- sum(vapply(journeys, function(j) { e <- j$events; length(e) > 1 && any(e[-1] == e[-length(e)]) }, logical(1)))
values <- list(n_entities = n, n_events = sum(lengths), n_types = length(types), mean_length = mean(lengths),
median_length = stats::median(lengths), max_length = max(lengths), n_paths = length(pcount),
top_path_share = pcount[[ranked[1]]] / n, repeat_share = repeat_n / n)
for (e in types) {
values[[sprintf("p_start[%s]", e)]] <- tr(START, e) / n
values[[sprintf("p_end[%s]", e)]] <- tr(e, END) / n
}
for (i in seq_along(trans_n)) values[[sprintf("p_trans[%s->%s]", from_of[i], to_of[i])]] <- trans_n[[i]] / from_tot[[from_of[i]]]
for (r in seq_len(min(10L, length(ranked)))) {
values[[sprintf("path_count[%d]", r)]] <- pcount[[ranked[r]]]
values[[sprintf("path_share[%d]", r)]] <- pcount[[ranked[r]]] / n
}
# %% Flow over the first steps (top events, the rest as Other)
keep <- utils::head(types, TOP_EVENTS)
nm <- function(e) ifelse(e %in% keep, e, "Other")
link_keys <- unlist(lapply(journeys, function(j) {
ev <- j$events
sq <- c(nm(utils::head(ev, STEPS)), rep(END, max(0, STEPS - length(ev))))
out <- character(0)
for (s in seq_len(STEPS - 1)) {
if (sq[s] == END) break
out <- c(out, paste(s, sprintf("%d: %s", s, sq[s]), sprintf("%d: %s", s + 1, sq[s + 1]), sep = "\u0001"))
}
out
}))
ltab <- table(link_keys)
lk <- names(ltab); lc <- as.integer(ltab)
parts <- strsplit(lk, "\u0001", fixed = TRUE)
lstep <- as.integer(vapply(parts, `[`, character(1), 1)); lsrc <- vapply(parts, `[`, character(1), 2); ltgt <- vapply(parts, `[`, character(1), 3)
lo <- order(lstep, lsrc, ltgt, method = "radix")
cols <- c(START, types)
tos <- c(types, END)
cs_publish(list(
title = "Event sequences and journeys",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("%d journeys, %d events of %d kinds; the most common path (%s) covers %.0f%%.", n, as.integer(sum(lengths)), length(types),
ranked[1], 100 * pcount[[ranked[1]]] / n),
statistics = list(list(key = "n_entities", label = "Journeys", value = n, format = "integer"),
list(key = "mean_length", label = "Mean length", value = mean(lengths)),
list(key = "top_path_share", label = "Top path", value = pcount[[ranked[1]]] / n, format = "percent")),
tables = list(
list(key = "paths", title = sprintf("Most common paths (first %d steps)", STEPS),
columns = list(list(key = "rank", label = "Rank", type = "integer"), list(key = "path", label = "Path"),
list(key = "count", label = "Journeys", type = "integer"), list(key = "share", label = "Share", type = "percent")),
rows = lapply(seq_len(min(20L, length(ranked))), function(r) list(rank = r, path = ranked[r], count = pcount[[ranked[r]]], share = pcount[[ranked[r]]] / n))),
list(key = "transitions", title = "What happens next (row → column probabilities)",
columns = c(list(list(key = "from", label = "From")), lapply(seq_along(tos), function(i) list(key = sprintf("to_%d", i - 1L), label = tos[i], type = "percent"))),
rows = lapply(Filter(function(a) !is.na(from_tot[a]), cols), function(a) {
r <- list(from = a)
for (i in seq_along(tos)) r[[sprintf("to_%d", i - 1L)]] <- tr(a, tos[i]) / from_tot[[a]]
r
}))
),
charts = list(cs_chart("flow", "sequence-sankey", sprintf("Journeys over the first %d steps", STEPS), list(
step = cs_col("Step", lstep[lo], "numeric"),
source = cs_col("From", lsrc[lo], "categorical"),
target = cs_col("To", ltgt[lo], "categorical"),
count = cs_col("Journeys", lc[lo], "numeric")
))),
values = values,
warnings = warnings
))
150 journeys, 896 events of 6 kinds; the most common path (visit → search → view → view) covers 13%.
- Journeys
- 150
- Mean length
- 5.973
- Top path
- 12.7%
To keep this page light, the plots are shown once, under the R tab.
Most common paths (first 4 steps)
| Rank | Path | Journeys | Share |
|---|---|---|---|
| 1 | visit → search → view → view | 19 | 12.7% |
| 2 | visit → search → view → cart | 11 | 7.3% |
| 3 | visit → search → view → search | 10 | 6.7% |
| 4 | visit → search → view → (end) | 9 | 6.0% |
| 5 | visit → view → cart → checkout | 9 | 6.0% |
| 6 | visit → search → search → view | 7 | 4.7% |
| 7 | visit → view → view → search | 6 | 4.0% |
| 8 | visit → support → view → cart | 5 | 3.3% |
| 9 | visit → view → search → view | 5 | 3.3% |
| 10 | visit → view → view → cart | 5 | 3.3% |
| 11 | visit → search → view → support | 4 | 2.7% |
| 12 | visit → support → view → view | 4 | 2.7% |
| 13 | visit → view → cart → view | 4 | 2.7% |
| 14 | visit → view → view → view | 4 | 2.7% |
| 15 | visit → search → support → search | 3 | 2.0% |
| 16 | visit → search → support → view | 3 | 2.0% |
| 17 | visit → support → view → (end) | 3 | 2.0% |
| 18 | visit → view → cart → (end) | 3 | 2.0% |
| 19 | visit → view → search → search | 3 | 2.0% |
| 20 | visit → view → support → search | 3 | 2.0% |
What happens next (row → column probabilities)
| From | view | search | visit | support | cart | checkout | (end) |
|---|---|---|---|---|---|---|---|
| (start) | 0.0% | 0.0% | 100.0% | 0.0% | 0.0% | 0.0% | 0.0% |
| view | 27.8% | 16.0% | 0.0% | 12.5% | 24.0% | 0.0% | 19.8% |
| search | 55.2% | 14.2% | 0.0% | 8.7% | 3.8% | 0.0% | 18.0% |
| visit | 37.1% | 47.2% | 0.0% | 14.5% | 0.0% | 0.0% | 1.3% |
| support | 33.0% | 24.1% | 0.0% | 15.2% | 6.3% | 0.0% | 21.4% |
| cart | 22.5% | 5.6% | 0.0% | 7.9% | 0.0% | 44.9% | 19.1% |
| checkout | 22.5% | 0.0% | 22.5% | 25.0% | 0.0% | 0.0% | 30.0% |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Event sequences and journeys
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sequences 1.0.0 · spec fdecb4a1d706db95
# Dataset: ds1_events (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.ml import discover_ext as dx
# %% Data
ENTITY = "customer"
TIME = "minute"
EVENT = "event"
STEPS = 4
TOP_EVENTS = 6
df = pd.read_parquet("tests/parity/fixtures/ds1_events.parquet", columns=list(dict.fromkeys([ENTITY, TIME, EVENT])))
warnings = []
ok = df[ENTITY].notna() & df[TIME].notna() & df[EVENT].notna()
if not ok.all():
warnings.append(f"{int((~ok).sum())} rows with a missing journey, time or event were left out.")
df = df[ok]
t = df[TIME]
key = t.to_numpy(dtype=np.float64) if pd.api.types.is_numeric_dtype(t) else pd.to_datetime(t).astype("int64").to_numpy(dtype=np.float64)
journeys = dx.sequences(df[ENTITY].astype("object").to_numpy(), key, df[EVENT].astype("object").to_numpy())
if not journeys:
raise ValueError("No complete events to analyze.")
# %% Counts
lengths = np.array([len(ev) for _, ev in journeys], dtype=np.float64)
counts: dict[str, int] = {}
for _, ev in journeys:
for e in ev:
counts[e] = counts.get(e, 0) + 1
types = sorted(counts, key=lambda e: (-counts[e], e)) # most frequent first, ties by name
START, END = "(start)", "(end)"
trans: dict[tuple[str, str], int] = {}
for _, ev in journeys:
chain = [START] + ev + [END]
for a, b in zip(chain[:-1], chain[1:]):
trans[(a, b)] = trans.get((a, b), 0) + 1
from_tot: dict[str, int] = {}
for (a, _), c in trans.items():
from_tot[a] = from_tot.get(a, 0) + c
paths: dict[str, int] = {}
for _, ev in journeys:
p = " → ".join(ev[:STEPS] + ([END] if len(ev) < STEPS else []))
paths[p] = paths.get(p, 0) + 1
ranked = sorted(paths, key=lambda p: (-paths[p], p))
n = len(journeys)
repeat = sum(1 for _, ev in journeys if any(a == b for a, b in zip(ev[:-1], ev[1:])))
values = {
"n_entities": n,
"n_events": int(lengths.sum()),
"n_types": len(types),
"mean_length": float(lengths.mean()),
"median_length": float(np.median(lengths)),
"max_length": int(lengths.max()),
"n_paths": len(paths),
"top_path_share": paths[ranked[0]] / n,
"repeat_share": repeat / n,
}
for e in types:
values[f"p_start[{e}]"] = trans.get((START, e), 0) / n
values[f"p_end[{e}]"] = trans.get((e, END), 0) / n
for (a, b), c in sorted(trans.items()):
values[f"p_trans[{a}->{b}]"] = c / from_tot[a]
for rank, p in enumerate(ranked[:10], start=1):
values[f"path_count[{rank}]"] = paths[p]
values[f"path_share[{rank}]"] = paths[p] / n
# %% Flow over the first steps (top events, the rest as Other)
keep = set(types[:TOP_EVENTS])
name = lambda e: e if e in keep else "Other" # noqa: E731
links: dict[tuple[int, str, str], int] = {}
for _, ev in journeys:
seq = [name(e) for e in ev[:STEPS]] + [END] * max(0, STEPS - len(ev))
for s in range(STEPS - 1):
if seq[s] == END:
break
k = (s + 1, f"{s + 1}: {seq[s]}", f"{s + 2}: {seq[s + 1]}")
links[k] = links.get(k, 0) + 1
ordered = sorted(links, key=lambda k: (k[0], k[1], k[2]))
cols = [START] + types
tos = types + [END]
cs.publish({
"title": "Event sequences and journeys",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": f"{n} journeys, {int(lengths.sum())} events of {len(types)} kinds; the most common path ({ranked[0]}) covers {paths[ranked[0]] / n:.0%}.",
"statistics": [
{"key": "n_entities", "label": "Journeys", "value": n, "format": "integer"},
{"key": "mean_length", "label": "Mean length", "value": float(lengths.mean())},
{"key": "top_path_share", "label": "Top path", "value": paths[ranked[0]] / n, "format": "percent"},
],
"tables": [
{
"key": "paths",
"title": f"Most common paths (first {STEPS} steps)",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "path", "label": "Path"},
{"key": "count", "label": "Journeys", "type": "integer"}, {"key": "share", "label": "Share", "type": "percent"}],
"rows": [{"rank": r, "path": p, "count": paths[p], "share": paths[p] / n} for r, p in enumerate(ranked[:20], start=1)],
},
{
"key": "transitions",
"title": "What happens next (row → column probabilities)",
"columns": [{"key": "from", "label": "From"}] + [{"key": f"to_{i}", "label": b, "type": "percent"} for i, b in enumerate(tos)],
"rows": [dict({"from": a}, **{f"to_{i}": (trans.get((a, b), 0) / from_tot[a]) if from_tot.get(a) else None for i, b in enumerate(tos)})
for a in cols if from_tot.get(a)],
},
],
"charts": [cs.chart("flow", "sequence-sankey", f"Journeys over the first {STEPS} steps", {
"step": cs.col("Step", [k[0] for k in ordered], "numeric"),
"source": cs.col("From", [k[1] for k in ordered], "categorical"),
"target": cs.col("To", [k[2] for k in ordered], "categorical"),
"count": cs.col("Journeys", [links[k] for k in ordered], "numeric"),
})],
"values": values,
"warnings": warnings,
})
150 journeys, 896 events, an average length of 6.0 events.
51% of journeys repeat an event. Loops matter: long paths with repeated visits to the help pages may show friction, or engagement. The numbers alone can't say which.
Order isn't cause
Reflect"People who visit pricing then buy" doesn't mean the pricing page sells. People who are about to buy check prices first.
To claim a cause you need a comparison, such as an experiment that changes the path. Look at a journey chart from your own work. Which conclusion did it invite, and what would you need to confirm it?
Check your understanding
CheckpointCheck yourself
Which columns does an event log need?
Show the answer
Answer: b
A row per customer has already thrown away the order. You need each event separately, so the app can sort it by time within each person.
Check yourself
A transition matrix says 40% of people go from "help page" to "cancel". What does this show?
Show the answer
Answer: b
It describes order, not cause or an overall rate. People already planning to cancel may look for help first.
Check yourself
Your timestamps only record the date, and several events share a date. What's the risk?
Show the answer
Answer: a
Ties keep their order in the data. If the file wasn't sorted by true time, the paths may be wrong, so use finer timestamps or a tie-breaking column if you have one.
Do it on your own data
In the appChoose Journeys & sequences, then set the entity, time and event columns.
import pandas as pd
df = pd.read_csv("events.csv").sort_values(["customer", "minute"], kind="stable")
paths = df.groupby("customer")["event"].apply(lambda s: " > ".join(s.head(4)))
print(paths.value_counts(normalize=True).head(5).round(3))
df["next"] = df.groupby("customer")["event"].shift(-1).fillna("(end)")
print(pd.crosstab(df["event"], df["next"], normalize="index").round(2))df <- read.csv("events.csv")
df <- df[order(df$customer, df$minute), ]
paths <- tapply(df$event, df$customer, function(s) paste(head(s, 4), collapse = " > "))
round(head(sort(prop.table(table(paths)), decreasing = TRUE), 5), 3)
nxt <- ave(df$event, df$customer, FUN = function(s) c(s[-1], "(end)"))
round(prop.table(table(df$event, nxt), 1), 2)Recap
Recap- Sequences need one row per event: who, when and what.
- A flow diagram shows divergence, and a transition matrix shows what comes next.
- Order isn't cause. Test before you claim that a path works.
Concepts in this lesson