Skip to content

CDiscover · discover.sequences

Event sequences and journeys

In what order do things happen — which journeys are common and where do people go next?

Turns an event log (who, when, what) into journeys: the most common paths over the first steps, next-event probabilities (a transition matrix with start and end), how journeys begin and end, and how long they are, with a flow diagram of the first steps. Events at the same time keep their order in the data. Counting is identical in both engines.

Verified in Python and R Python and R agree to 10 decimals Also called sequence analysis, journey analysis, path analysis…

A real result

Example “Journeys”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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%
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%

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Journeysds1_events · entity: customer · event: event · time: minute
  • Journeys shortds1_events · entity: customer · event: event · time: minute

In the guides

Where it sits in the decision guides

  • Association rules (Apriori, FP-Growth) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Who (journey id)categorical / numeric · 1 column
Each value is one journey: a customer, session, patient or machine.
Whentemporal / numeric · 1 column
Orders the events within a journey (ties keep the data's order).
What happenedcategorical · 1 column
The event or state at that time (page, step, status).

Choices you make

model

Steps in a pathdefault 4

Journeys are compared on their first this-many events.

options

Events shown in the flowdefault 6

The most frequent events get their own band; the rest are grouped as Other.

What it reports

n_entities
How many independent units the analysis used; it sets precision and power.
n_events
How many independent units the analysis used; it sets precision and power.
n_types
How many independent units the analysis used; it sets precision and power.
mean_length
Summarizes ordered events per entity — common paths, what happens next and where journeys end.
median_length
Summarizes ordered events per entity — common paths, what happens next and where journeys end.
max_length
Summarizes ordered events per entity — common paths, what happens next and where journeys end.
n_paths
How many independent units the analysis used; it sets precision and power.
top_path_share
Summarizes ordered events per entity — common paths, what happens next and where journeys end.
repeat_share
Summarizes ordered events per entity — common paths, what happens next and where journeys end.

Per group, level or term: p_start[<event>], p_end[<event>], p_trans[<from>-><to>], path_count[<rank>], path_share[<rank>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-12). Python uses pandas; R uses codesplashr.

Default traps between the two languages

  • Pure counting, identical in both engines. TraMineR (R) and pm4py (Python) offer richer sequence clustering and process maps; those are not used here.
Python

The exact script CodeSplash ran for example “Journeys” · 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,
})
R

The exact script CodeSplash ran for example “Journeys” · 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
))

Sources

  • Gabadinho A, Ritschard G, Müller NS, Studer M (2011). Analyzing and visualizing state sequences in R with TraMineR. J Stat Software 40(4).
  • van der Aalst W (2016). Process Mining: Data Science in Action. Springer.

From the CodeSplash method registry · discover.sequences v1.0.0.