"""Sequence databases, sequential patterns and containment.
A *sequence* is an ordered list of non-empty itemsets (elements); most event
logs have exactly one item per element. A *pattern* has the same structure and
is written as a tuple of tuples: ``(("a",), ("b", "c"))`` is the pattern
:math:`\\langle a\\,(bc)\\rangle`. Every public function of the package also
accepts patterns as strings (``"a b c"``, ``"a (b c)"``, ``"a -> b"``) or lists.
"""
from __future__ import annotations
import math
import re
from collections import Counter
from collections.abc import Hashable, Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
import numpy as np
import pandas as pd
__all__ = [
"Constraints",
"SequenceDatabase",
"as_pattern",
"contains",
"find_occurrence",
"format_pattern",
"is_subpattern",
"item_key",
"parent_pattern",
"pattern_items",
"pattern_length",
]
Pattern = tuple # tuple[tuple[Hashable, ...], ...]
# ---------------------------------------------------------------------------
# items and patterns
# ---------------------------------------------------------------------------
[docs]
def item_key(x: Any) -> tuple:
"""Sort key giving a total order over mixed items: numbers first, then strings."""
if isinstance(x, bool):
return (0, int(x), "")
if isinstance(x, (int, float, np.integer, np.floating)):
return (0, float(x), "")
return (1, 0.0, str(x))
def _is_itemset(x: Any) -> bool:
return isinstance(x, (list, tuple, set, frozenset))
def _norm_itemset(x: Any) -> tuple:
if _is_itemset(x):
items = list(dict.fromkeys(x))
else:
items = [x]
items = [_py(i) for i in items]
return tuple(sorted(items, key=item_key))
def _py(x: Any) -> Any:
"""Convert numpy scalars to Python scalars so that patterns hash and print cleanly."""
if isinstance(x, np.generic):
return x.item()
return x
_TOKEN = re.compile(r"\(|\)|\{|\}|[^\s(){},]+")
def _parse_pattern_string(text: str) -> tuple:
s = text.strip()
if s.startswith("<") and s.endswith(">"):
s = s[1:-1]
s = s.replace("⟨", " ").replace("⟩", " ")
if re.search(r"→|->|=>", s) and "-1" not in s.split():
# arrow notation (the default of format_pattern): every part between two
# arrows is one element, so items may contain spaces ("wake up -> coffee");
# "(a, b)" is an itemset
elements = []
for part in re.split(r"\s*(?:→|->|=>)\s*", s.strip()):
part = part.strip()
if not part:
continue
if part[0] in "({" and part[-1] in ")}":
elements.append(_norm_itemset([t.strip() for t in re.split(r",", part[1:-1]) if t.strip()]))
else:
elements.append((part,))
return tuple(elements)
s = s.replace("→", " ").replace("->", " ").replace("=>", " ")
if "-1" in s.split(): # SPMF format "1 -1 2 3 -1 -2" (items may also be words)
elements, current = [], []
for tok in s.split():
if tok == "-1":
if current:
elements.append(tuple(current))
current = []
elif tok == "-2":
break
else:
try:
current.append(int(tok))
except ValueError:
current.append(tok)
if current:
elements.append(tuple(current))
return tuple(_norm_itemset(e) for e in elements)
elements: list = []
group: list | None = None
for tok in _TOKEN.findall(s):
if tok in "({":
group = []
elif tok in ")}":
if group:
elements.append(_norm_itemset(group))
group = None
elif group is not None:
group.append(tok)
else:
elements.append((tok,))
return tuple(elements)
[docs]
def as_pattern(p: Any, alphabet: Mapping[str, Hashable] | None = None) -> Pattern:
"""Normalize a pattern given as tuple of tuples, list or string.
Parameters
----------
p : tuple, list or str
``(("a",), ("b", "c"))``, ``["a", ["b", "c"]]``, ``"a (b c)"``,
arrow notation ``"a -> b -> (c, d)"`` (items between arrows may contain
spaces) or SPMF notation ``"1 -1 2 3 -1"``. Without arrows, whitespace
separates items.
alphabet : mapping, optional
Maps the string form of the items of a database to the items themselves,
so that ``"1 2"`` resolves to integer items. ``SequenceDatabase.pattern``
passes its own alphabet.
Returns
-------
tuple of tuple
The pattern in canonical form (items of an itemset in natural order).
Examples
--------
>>> as_pattern("a (c b) d")
(('a',), ('b', 'c'), ('d',))
>>> as_pattern(["x", "y"])
(('x',), ('y',))
>>> as_pattern("wake up -> coffee -> (tv, read)")
(('wake up',), ('coffee',), ('read', 'tv'))
"""
if isinstance(p, str):
pat = _parse_pattern_string(p)
elif isinstance(p, (int, np.integer)):
pat = ((_py(p),),)
else:
pat = tuple(_norm_itemset(e) for e in p)
if alphabet is not None:
pat = tuple(_norm_itemset([alphabet.get(str(i), i) for i in e]) for e in pat)
return pat
[docs]
def pattern_length(p: Pattern) -> int:
"""Number of items of a pattern."""
return sum(len(e) for e in p)
[docs]
def pattern_items(p: Pattern) -> list:
"""Items of a pattern in order of appearance (with repetitions)."""
return [i for e in p for i in e]
[docs]
def parent_pattern(p: Pattern) -> Pattern:
"""The pattern with its last item removed (the empty tuple for single items)."""
if not p:
return ()
last = p[-1]
if len(last) == 1:
return p[:-1]
return p[:-1] + (last[:-1],)
[docs]
def is_subpattern(p: Pattern, q: Pattern) -> bool:
"""Whether pattern ``p`` is contained in pattern ``q`` (no gap constraints)."""
j = 0
for e in p:
se = set(e)
while j < len(q) and not se.issubset(q[j]):
j += 1
if j == len(q):
return False
j += 1
return True
# ---------------------------------------------------------------------------
# constraints and containment
# ---------------------------------------------------------------------------
[docs]
@dataclass(frozen=True)
class Constraints:
"""Gap and span constraints of an occurrence.
Parameters
----------
min_gap, max_gap : int or float, optional
Bounds on the distance of consecutive matched elements, :math:`g_{\\min}\\le
j_{k+1}-j_k\\le g_{\\max}`. In index units (default) ``max_gap=1`` means
adjacent elements (SPMF convention) and ``min_gap`` defaults to 1. In time
units (``gap_unit="time"``) the bounds apply to timestamp differences and
``min_gap`` defaults to 0.
max_span : int or float, optional
Bound on :math:`j_m-j_1` (or :math:`t_{j_m}-t_{j_1}`).
gap_unit : {"index", "time"}
"""
min_gap: float | None = None
max_gap: float | None = None
max_span: float | None = None
gap_unit: str = "index"
def __post_init__(self):
if self.gap_unit not in ("index", "time"):
raise ValueError("gap_unit must be 'index' or 'time'")
if self.max_gap is not None and self.max_gap <= 0:
raise ValueError("max_gap must be positive")
@property
def lo(self) -> float:
if self.min_gap is not None:
return self.min_gap
return 1 if self.gap_unit == "index" else 0
@property
def unconstrained(self) -> bool:
return self.max_gap is None and self.max_span is None and self.lo <= (1 if self.gap_unit == "index" else 0)
def as_dict(self) -> dict:
return {"min_gap": self.min_gap, "max_gap": self.max_gap, "max_span": self.max_span, "gap_unit": self.gap_unit}
def _constraints(constraints: Constraints | None, **kw) -> Constraints:
if constraints is not None:
return constraints
kw = {k: v for k, v in kw.items() if k in ("min_gap", "max_gap", "max_span", "gap_unit") and v is not None}
return Constraints(**kw)
[docs]
def find_occurrence(
sequence: Sequence,
pattern: Any,
constraints: Constraints | None = None,
times: Sequence[float] | None = None,
start: int = 0,
**kw,
) -> list[int] | None:
"""Element indices of the earliest-ending occurrence of a pattern, or ``None``.
Parameters
----------
sequence : sequence of itemsets
pattern : pattern
constraints : Constraints, optional
Or the keywords ``min_gap``, ``max_gap``, ``max_span``, ``gap_unit``.
times : sequence of float, optional
Timestamps of the elements, required when ``gap_unit="time"``.
start : int
First element index that may be matched.
Examples
--------
>>> find_occurrence(["a", "b", "x", "c"], "a c")
[0, 3]
>>> find_occurrence(["a", "b", "x", "c"], "a c", max_gap=2) is None
True
"""
con = _constraints(constraints, **kw)
pat = as_pattern(pattern)
seq = [frozenset(e) if _is_itemset(e) else frozenset([e]) for e in sequence]
m, L = len(pat), len(seq)
if m == 0:
return []
if con.gap_unit == "time" and times is None:
raise ValueError("gap_unit='time' needs timestamps")
sets = [set(e) for e in pat]
if con.unconstrained:
pos, j = [], start
for e in sets:
while j < L and not e.issubset(seq[j]):
j += 1
if j == L:
return None
pos.append(j)
j += 1
return pos
t = None if times is None else np.asarray(times, dtype=float)
def dist(a: int, b: int) -> float:
return (b - a) if con.gap_unit == "index" else (t[b] - t[a])
lo, hi, span = con.lo, con.max_gap, con.max_span
# layer k: end position -> (latest start, predecessor end)
layer: dict[int, tuple[int, int | None]] = {q: (q, None) for q in range(start, L) if sets[0].issubset(seq[q])}
if not layer:
return None
layers = [layer]
for k in range(1, m):
nxt: dict[int, tuple[int, int | None]] = {}
for q in sorted(layer):
st = layer[q][0]
for q2 in range(q + 1, L):
d = dist(q, q2)
if hi is not None and d > hi:
break
if d < lo:
continue
if span is not None and dist(st, q2) > span:
break
if sets[k].issubset(seq[q2]):
if q2 not in nxt or nxt[q2][0] < st:
nxt[q2] = (st, q)
if not nxt:
return None
layer = nxt
layers.append(layer)
end = min(layer)
pos = [end]
for k in range(m - 1, 0, -1):
end = layers[k][end][1]
pos.append(end)
return pos[::-1]
[docs]
def contains(sequence: Sequence, pattern: Any, constraints: Constraints | None = None, times=None, **kw) -> bool:
"""Whether a sequence contains a pattern under the given constraints.
Examples
--------
>>> contains(["a", ("b", "c"), "d"], "a (b c)")
True
>>> contains(["a", "b", "c"], "a c", max_gap=1)
False
"""
return find_occurrence(sequence, pattern, constraints, times, **kw) is not None
# ---------------------------------------------------------------------------
# sequence database
# ---------------------------------------------------------------------------
@dataclass
class _Encoded:
seqs: list # list[list[tuple[int, ...]]]
items: list # code -> item
code: dict # item -> code
[docs]
class SequenceDatabase:
"""A database of sequences of itemsets with optional timestamps and attributes.
Parameters
----------
sequences : iterable
Each sequence is an iterable of elements; an element is an item or an
iterable of items (an itemset). A string is split into its characters.
times : iterable of array-like, optional
One timestamp per element (numbers or datetimes; datetimes are stored as
seconds since the Unix epoch).
ids : sequence, optional
Identifiers of the sequences (case ids); default ``0..n-1``.
attributes : pandas.DataFrame, optional
One row per sequence (group, outcome, ...).
labels : mapping, optional
Display names of the items, used by every table and figure.
name : str, optional
Examples
--------
>>> db = SequenceDatabase(["abc", "acd", "bcd"])
>>> db.n_sequences, db.alphabet
(3, ['a', 'b', 'c', 'd'])
>>> db.support("a c")
2
"""
def __init__(
self,
sequences: Iterable,
times: Iterable | None = None,
ids: Sequence | None = None,
attributes: pd.DataFrame | None = None,
labels: Mapping | None = None,
name: str | None = None,
):
seqs = []
for s in sequences:
if isinstance(s, str):
s = list(s)
seqs.append(tuple(_norm_itemset(e) for e in s if not (_is_itemset(e) and len(e) == 0)))
self._seqs: list[tuple] = seqs
n = len(seqs)
self.times: list[np.ndarray] | None = None
self.time_is_datetime = False
if times is not None:
times = list(times)
tl = []
for s, t in zip(seqs, times, strict=True):
arr = _to_seconds(t)
if len(arr) != len(s):
raise ValueError("every sequence needs one timestamp per element")
tl.append(arr)
self.times = tl
self.time_is_datetime = any(_is_datetime_like(t) for t in times)
self.ids = list(range(n)) if ids is None else [_py(i) for i in ids]
if len(self.ids) != n:
raise ValueError("ids must have one entry per sequence")
if attributes is not None:
attributes = pd.DataFrame(attributes).reset_index(drop=True)
if len(attributes) != n:
raise ValueError("attributes must have one row per sequence")
self.attributes = attributes
self.labels = dict(labels) if labels else {}
self.name = name
self._enc: _Encoded | None = None
# -- construction --------------------------------------------------------
[docs]
@classmethod
def from_strings(cls, strings: Iterable[str], sep: str | None = None, **kw) -> SequenceDatabase:
"""Each string is a sequence; ``sep=None`` splits into characters, otherwise on ``sep``.
Examples
--------
>>> SequenceDatabase.from_strings(["wake shower coffee"], sep=" ")[0]
(('wake',), ('shower',), ('coffee',))
"""
seqs = [list(s) if sep is None else [t for t in s.split(sep) if t] for s in strings]
return cls(seqs, **kw)
[docs]
@classmethod
def from_event_log(
cls,
df: pd.DataFrame,
case: str = "case",
activity: str = "activity",
timestamp: str | None = None,
group_simultaneous: bool = False,
attributes: Sequence[str] | None = None,
labels: Mapping | None = None,
name: str | None = None,
sort: bool = True,
) -> SequenceDatabase:
"""Build sequences from a long event table (one row per event).
Parameters
----------
df : pandas.DataFrame
case, activity : str
Columns of the case (sequence) identifier and of the item.
timestamp : str, optional
Column used to order the events of a case (stable sort) and stored as
the element timestamps. Without it the row order is kept.
group_simultaneous : bool
Events of a case with equal timestamps form one itemset.
attributes : list of str, optional
Case-level columns copied (first value per case) into ``attributes``.
sort : bool
Order the events of a case by ``timestamp`` (stable). With ``False`` the
row order is kept and the timestamps are only attached.
Examples
--------
>>> log = pd.DataFrame({"case": [1, 1, 2], "activity": ["a", "b", "a"]})
>>> SequenceDatabase.from_event_log(log).n_sequences
2
"""
data = df
if timestamp is not None:
data = df.assign(_t=_to_seconds(df[timestamp]))
if sort:
data = data.sort_values([case, "_t"], kind="stable")
order = pd.unique(df[case])
else:
order = pd.unique(df[case])
groups = {k: g for k, g in data.groupby(case, sort=False)}
seqs, times, ids, attrs = [], [], [], []
for k in order:
g = groups[k]
acts = [_py(a) for a in g[activity].tolist()]
if timestamp is not None:
ts = g["_t"].to_numpy(dtype=float)
if group_simultaneous:
elems, et = [], []
for a, t in zip(acts, ts, strict=True):
if et and t == et[-1]:
elems[-1].append(a)
else:
elems.append([a])
et.append(t)
seqs.append(elems)
times.append(np.asarray(et))
else:
seqs.append(acts)
times.append(ts)
else:
seqs.append(acts)
ids.append(_py(k))
if attributes:
attrs.append({a: g[a].iloc[0] for a in attributes})
db = cls(
seqs,
times=times if timestamp is not None else None,
ids=ids,
attributes=pd.DataFrame(attrs) if attributes else None,
labels=labels,
name=name,
)
if timestamp is not None:
db.time_is_datetime = _is_datetime_like(df[timestamp])
return db
[docs]
@classmethod
def from_wide(cls, df: pd.DataFrame, columns: Sequence | None = None, collapse: bool = False, **kw):
"""State sequences stored in columns (one row per sequence, as in TraMineR).
Missing values end a sequence. With ``collapse=True`` runs of the same
state become one element (the *distinct successive states* view).
"""
cols = list(df.columns) if columns is None else list(columns)
seqs = []
for _, row in df[cols].iterrows():
s = [_py(v) for v in row.tolist() if not (v is None or (isinstance(v, float) and math.isnan(v)))]
if collapse:
s = [v for i, v in enumerate(s) if i == 0 or v != s[i - 1]]
seqs.append(s)
return cls(seqs, **kw)
[docs]
@classmethod
def from_spmf(cls, path, **kw) -> SequenceDatabase:
"""Read a sequence database in SPMF format (see :func:`spmviz.io.read_spmf`)."""
from .io import read_spmf
return read_spmf(path, **kw)
[docs]
@classmethod
def from_pm4py(cls, log, case: str = "case:concept:name", activity: str = "concept:name",
timestamp: str = "time:timestamp", **kw) -> SequenceDatabase:
"""Convert a pm4py event log (``EventLog`` or the pm4py pandas format)."""
if not isinstance(log, pd.DataFrame):
import pm4py # optional
log = pm4py.convert_to_dataframe(log)
ts = timestamp if timestamp in log.columns else None
return cls.from_event_log(log, case=case, activity=activity, timestamp=ts, **kw)
# -- container protocol --------------------------------------------------
def __len__(self) -> int:
return len(self._seqs)
def __iter__(self) -> Iterator[tuple]:
return iter(self._seqs)
def __getitem__(self, key):
if isinstance(key, (int, np.integer)):
return self._seqs[int(key)]
if isinstance(key, slice):
idx = list(range(len(self)))[key]
else:
idx = list(np.arange(len(self))[np.asarray(key)]) if np.asarray(key).dtype == bool else list(key)
return self.subset(idx)
def __repr__(self) -> str:
nm = f"{self.name!r}, " if self.name else ""
return (f"SequenceDatabase({nm}n_sequences={len(self)}, n_items={self.n_items}, "
f"avg_length={self.lengths.mean() if len(self) else 0:.2f})")
# -- properties ----------------------------------------------------------
@property
def sequences(self) -> list[tuple]:
"""The sequences as tuples of itemsets."""
return list(self._seqs)
@property
def n_sequences(self) -> int:
return len(self._seqs)
@property
def alphabet(self) -> list:
"""Sorted list of the distinct items."""
return list(self._encoded().items)
@property
def n_items(self) -> int:
return len(self._encoded().items)
@property
def lengths(self) -> np.ndarray:
"""Number of elements of every sequence."""
return np.array([len(s) for s in self._seqs], dtype=int)
@property
def is_simple(self) -> bool:
"""True when every element holds a single item."""
return all(len(e) == 1 for s in self._seqs for e in s)
@property
def has_times(self) -> bool:
return self.times is not None
[docs]
def item_support(self) -> pd.Series:
"""Number of sequences containing each item, sorted decreasingly."""
c = Counter(i for s in self._seqs for i in {i for e in s for i in e})
return pd.Series(c, dtype=int).sort_values(ascending=False, kind="stable")
[docs]
def item_frequency(self) -> pd.Series:
"""Number of occurrences of each item."""
c = Counter(i for s in self._seqs for e in s for i in e)
return pd.Series(c, dtype=int).sort_values(ascending=False, kind="stable")
[docs]
def stats(self) -> pd.Series:
"""Summary statistics (the columns of the benchmark tables in the literature)."""
L = self.lengths
n_el = int(L.sum())
n_it = sum(len(e) for s in self._seqs for e in s)
distinct = np.array([len({i for e in s for i in e}) for s in self._seqs]) if len(self) else np.array([0])
return pd.Series(
{
"n_sequences": len(self),
"n_items": self.n_items,
"n_elements": n_el,
"avg_length": L.mean() if len(L) else 0.0,
"min_length": int(L.min()) if len(L) else 0,
"max_length": int(L.max()) if len(L) else 0,
"avg_itemset_size": n_it / n_el if n_el else 0.0,
"avg_distinct_items": float(distinct.mean()),
"density": float(distinct.mean() / self.n_items) if self.n_items else 0.0,
}
)
[docs]
def label(self, item: Hashable) -> str:
"""Display name of an item."""
return str(self.labels.get(item, item))
[docs]
def pattern(self, p: Any) -> Pattern:
"""Resolve a pattern written with the items, their string form or their labels.
Examples
--------
>>> db = SequenceDatabase([[1, 2], [2, 3]], labels={1: "login", 2: "search", 3: "buy"})
>>> db.pattern("login -> search"), db.pattern("2 3")
(((1,), (2,)), ((2,), (3,)))
"""
items = self._encoded().items
alphabet = {str(self.label(i)): i for i in items} if self.labels else {}
alphabet.update({str(i): i for i in items})
return as_pattern(p, alphabet)
# -- encoding (used by the miners) ----------------------------------------
def _encoded(self) -> _Encoded:
if self._enc is None:
items = sorted({i for s in self._seqs for e in s for i in e}, key=item_key)
code = {it: k for k, it in enumerate(items)}
seqs = [[tuple(code[i] for i in e) for e in s] for s in self._seqs]
self._enc = _Encoded(seqs, items, code)
return self._enc
# -- queries ---------------------------------------------------------------
[docs]
def contains(self, pattern: Any, constraints: Constraints | None = None, **kw) -> np.ndarray:
"""Boolean array: which sequences contain the pattern."""
pat = self.pattern(pattern)
con = _constraints(constraints, **kw)
out = np.zeros(len(self), dtype=bool)
for i, s in enumerate(self._seqs):
t = None if self.times is None else self.times[i]
out[i] = find_occurrence(s, pat, con, t) is not None
return out
[docs]
def support(self, pattern: Any, constraints: Constraints | None = None, **kw) -> int:
"""Number of sequences that contain the pattern."""
return int(self.contains(pattern, constraints, **kw).sum())
# -- transformations --------------------------------------------------------
[docs]
def subset(self, idx: Sequence[int]) -> SequenceDatabase:
"""A new database with the selected sequences (ids, times and attributes follow)."""
idx = [int(i) for i in idx]
db = SequenceDatabase.__new__(SequenceDatabase)
db._seqs = [self._seqs[i] for i in idx]
db.times = None if self.times is None else [self.times[i] for i in idx]
db.time_is_datetime = self.time_is_datetime
db.ids = [self.ids[i] for i in idx]
db.attributes = None if self.attributes is None else self.attributes.iloc[idx].reset_index(drop=True)
db.labels = dict(self.labels)
db.name = self.name
db._enc = None
return db
[docs]
def filter(self, min_length: int | None = None, max_length: int | None = None,
contains: Any = None, **constraints) -> SequenceDatabase:
"""Sequences with length in a range and/or containing a pattern."""
keep = np.ones(len(self), dtype=bool)
L = self.lengths
if min_length is not None:
keep &= L >= min_length
if max_length is not None:
keep &= L <= max_length
if contains is not None:
keep &= self.contains(contains, **constraints)
return self.subset(np.flatnonzero(keep))
[docs]
def sample(self, n: int, random_state=None) -> SequenceDatabase:
"""Random sample of ``n`` sequences without replacement."""
rng = np.random.default_rng(random_state)
idx = np.sort(rng.choice(len(self), size=min(n, len(self)), replace=False))
return self.subset(idx)
[docs]
def split(self, by: str | Sequence) -> dict:
"""Split by an attribute column (or an array of group labels) into a dict of databases."""
labels = self.attributes[by].to_numpy() if isinstance(by, str) else np.asarray(by)
return {_py(g): self.subset(np.flatnonzero(labels == g)) for g in pd.unique(labels)}
[docs]
def map_items(self, mapping: Mapping | Any) -> SequenceDatabase:
"""Rename items with a dict or a function (e.g. to merge similar events)."""
f = mapping.get if isinstance(mapping, Mapping) else mapping
g = (lambda i: f(i, i)) if isinstance(mapping, Mapping) else f
db = SequenceDatabase([[tuple(g(i) for i in e) for e in s] for s in self._seqs],
times=self.times, ids=self.ids, attributes=self.attributes, name=self.name)
db.time_is_datetime = self.time_is_datetime
return db
[docs]
def to_lists(self) -> list:
"""Plain Python lists: items for simple databases, lists of itemsets otherwise."""
if self.is_simple:
return [[e[0] for e in s] for s in self._seqs]
return [[list(e) for e in s] for s in self._seqs]
[docs]
def to_event_log(self, case: str = "case", activity: str = "activity", timestamp: str = "timestamp") -> pd.DataFrame:
"""Long event table: one row per item (elements keep a shared position/timestamp)."""
rows = []
for k, s in enumerate(self._seqs):
for j, e in enumerate(s):
t = self.times[k][j] if self.times is not None else j
for i in e:
rows.append((self.ids[k], i, t, j))
df = pd.DataFrame(rows, columns=[case, activity, timestamp, "position"])
if self.times is not None and self.time_is_datetime:
df[timestamp] = pd.to_datetime(df[timestamp], unit="s")
return df
[docs]
def describe(self) -> pd.DataFrame:
"""``stats()`` as a one-column table (handy in notebooks)."""
return self.stats().to_frame(self.name or "value")
def _is_datetime_like(x) -> bool:
import datetime as _dt
try:
if isinstance(x, pd.Series):
if pd.api.types.is_datetime64_any_dtype(x):
return True
x = x.tolist()
arr = np.asarray(x)
if np.issubdtype(arr.dtype, np.datetime64):
return True
if arr.dtype == object and arr.size:
first = arr.flat[0]
if isinstance(first, (pd.Timestamp, _dt.datetime, np.datetime64)):
return True
if isinstance(first, str):
try:
pd.to_datetime(first)
return not first.strip().lstrip("-").replace(".", "", 1).isdigit()
except (ValueError, TypeError):
return False
return False
except Exception: # pragma: no cover - defensive
return False
def _to_seconds(t) -> np.ndarray:
"""Convert timestamps (numbers, datetimes, strings) to float seconds."""
if isinstance(t, pd.Series):
if pd.api.types.is_numeric_dtype(t):
return t.to_numpy(dtype=float)
dt = pd.to_datetime(t, format="mixed") if t.dtype == object or pd.api.types.is_string_dtype(t) else pd.to_datetime(t)
if getattr(dt.dt, "tz", None) is not None:
dt = dt.dt.tz_convert("UTC").dt.tz_localize(None)
return (dt - pd.Timestamp("1970-01-01")).dt.total_seconds().to_numpy(dtype=float)
arr = np.asarray(t)
if arr.dtype.kind in "iuf":
return arr.astype(float)
if arr.dtype.kind == "M":
return (arr.astype("datetime64[ns]").astype("int64") / 1e9).astype(float)
return _to_seconds(pd.Series(list(arr)))