Skip to content

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.

Applied ~10 min9 steps

What runs in CodeSplash

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
01

Order is the data

Read

Counts 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.

02

Make a guess

Predict

Predict 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.

03

Read the flow

Explore
Journey flowWhere do journeys go from each step to the next?
View data
stepfromtojourneys
11: visit2: (end)48
11: visit2: search153
11: visit2: view199
22: search3: (end)16
22: search3: cart11
22: search3: search9
22: search3: view117
22: view3: (end)33
22: view3: cart59
22: view3: search36
22: view3: view71
33: cart4: (end)11
33: cart4: checkout39
33: cart4: search6
33: cart4: view14
33: search4: (end)5
33: search4: search5
33: search4: view35
33: view4: (end)17
33: view4: cart71
33: view4: search31
33: view4: view69

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.

04

What happens next?

Read

The 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.

05

Read the card

Read
Event sequences and journeysRecorded · Python and R agreeRecorded 2026-11-17 · 70 values compared
R

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%

Plots

Journeys over the first 4 stepsWhere do journeys go from each step to the next?
View data
JourneysFromStepTo
741: visit12: search
221: visit12: support
541: visit12: view
12: search23: cart
132: search23: search
72: search23: support
532: search23: view
32: support23: cart
32: support23: search
22: support23: support
142: support23: view
182: view23: cart
122: view23: search
72: view23: support
172: view23: view
43: cart34: (end)
113: cart34: checkout
23: cart34: support
53: cart34: view
53: search34: (end)
23: search34: cart
63: search34: search
23: search34: support
133: search34: view
33: support34: (end)
63: support34: search
13: support34: support
63: support34: view
133: view34: (end)
213: view34: cart
173: view34: search
63: view34: support
273: view34: view

Most common paths (first 4 steps)

RankPathJourneysShare
1visit → search → view → view1912.7%
2visit → search → view → cart117.3%
3visit → search → view → search106.7%
4visit → search → view → (end)96.0%
5visit → view → cart → checkout96.0%
6visit → search → search → view74.7%
7visit → view → view → search64.0%
8visit → support → view → cart53.3%
9visit → view → search → view53.3%
10visit → view → view → cart53.3%
11visit → search → view → support42.7%
12visit → support → view → view42.7%
13visit → view → cart → view42.7%
14visit → view → view → view42.7%
15visit → search → support → search32.0%
16visit → search → support → view32.0%
17visit → support → view → (end)32.0%
18visit → view → cart → (end)32.0%
19visit → view → search → search32.0%
20visit → view → support → search32.0%

What happens next (row → column probabilities)

Fromviewsearchvisitsupportcartcheckout(end)
(start)0.0%0.0%100.0%0.0%0.0%0.0%0.0%
view27.8%16.0%0.0%12.5%24.0%0.0%19.8%
search55.2%14.2%0.0%8.7%3.8%0.0%18.0%
visit37.1%47.2%0.0%14.5%0.0%0.0%1.3%
support33.0%24.1%0.0%15.2%6.3%0.0%21.4%
cart22.5%5.6%0.0%7.9%0.0%44.9%19.1%
checkout22.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
))
Python

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)

RankPathJourneysShare
1visit → search → view → view1912.7%
2visit → search → view → cart117.3%
3visit → search → view → search106.7%
4visit → search → view → (end)96.0%
5visit → view → cart → checkout96.0%
6visit → search → search → view74.7%
7visit → view → view → search64.0%
8visit → support → view → cart53.3%
9visit → view → search → view53.3%
10visit → view → view → cart53.3%
11visit → search → view → support42.7%
12visit → support → view → view42.7%
13visit → view → cart → view42.7%
14visit → view → view → view42.7%
15visit → search → support → search32.0%
16visit → search → support → view32.0%
17visit → support → view → (end)32.0%
18visit → view → cart → (end)32.0%
19visit → view → search → search32.0%
20visit → view → support → search32.0%

What happens next (row → column probabilities)

Fromviewsearchvisitsupportcartcheckout(end)
(start)0.0%0.0%100.0%0.0%0.0%0.0%0.0%
view27.8%16.0%0.0%12.5%24.0%0.0%19.8%
search55.2%14.2%0.0%8.7%3.8%0.0%18.0%
visit37.1%47.2%0.0%14.5%0.0%0.0%1.3%
support33.0%24.1%0.0%15.2%6.3%0.0%21.4%
cart22.5%5.6%0.0%7.9%0.0%44.9%19.1%
checkout22.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.

06

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?

07

Check your understanding

Checkpoint

Check 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.

08

Do it on your own data

In the app

Choose Journeys & sequences, then set the entity, time and event columns.

Python
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))
R
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)
09

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