Skip to main content
Version: 0.0.98

ts_shape.utils.frames

Input checks shared by every public function outside the detectors.

The detectors in :mod:ts_shape.events get their input checks from :class:~ts_shape.utils.base.Base. Transforms, features, signals, the event log and the context helpers use these functions, so a missing column, an untyped time column or a time bound in another timezone is handled the same way everywhere:

  • :func:require_columns -- a missing column raises :class:~ts_shape.errors.ColumnNotFoundError naming the function.
  • :func:as_datetime -- a time column as datetime64 (text parsed, pyarrow timestamps converted, an empty untyped column typed).
  • :func:same_time_axis -- two time columns with one unit and the same timezone handling, so they can be merged or compared.
  • :func:localize_like -- a time bound (data_end, start) in the timezone of the data.
  • :func:ffill_values -- forward-fill that keeps the dtype (no silent downcasting of object columns).
  • :func:to_ns -- times as int64 nanoseconds since the epoch (UTC instants for tz-aware values), for NumPy searches and sorts.
  • :func:signal_frame_input -- decorator: a computing classmethod works on a normalized copy of its input frame.
Functions
NameDescription
require_columnsRaise when dataframe lacks any of columns.
as_datetimeReturn series as a NumPy datetime64 Series.
same_time_axisBring two time columns to one unit, so they can be merged.
localize_likeReturn value as a Timestamp in the timezone of reference.
localize_inReturn value as a Timestamp in tz (naive when tz is None).
to_nsTimes as int64 nanoseconds since the epoch.
ffill_valuesForward-fill series and keep its dtype.
signal_frame_inputRun a computing classmethod on a normalized copy of its frame.
window_offsetThe pandas offset of window, with "D" as a calendar day.
compact_frameA long-format frame in less memory, same values.

require_columns​

functionsource
require_columns(
dataframe: pd.DataFrame, columns: Iterable[str | None], *, where: str | None
) -> None

Raise when dataframe lacks any of columns.

Parameters
NameTypeDescriptionDefault
dataframeDataFrameInput frame.required
columnsIterable[str | None]Required column names; None entries are skipped.required
wherestr | NoneName of the calling function, used as the message prefix; None leaves the prefix out.required
Raises
TypeDescription
ColumnNotFoundErrorNaming the missing columns and the available ones. Subclasses ValueError.

as_datetime​

functionsource
as_datetime(series: pd.Series, *, where: str) -> pd.Series

Return series as a NumPy datetime64 Series.

Text is parsed, a pyarrow timestamp becomes datetime64 with the same timezone, and an empty column of any dtype becomes datetime64[ns].

Parameters
NameTypeDescriptionDefault
seriesSeriesTime values.required
wherestrName of the calling function, used in the message.required
Returns
TypeDescription
SeriesThe values as datetime64 (tz-aware when the input is).
Raises
TypeDescription
ValueErrorWhen non-empty values cannot be read as times.

same_time_axis​

functionsource
same_time_axis(
left: pd.Series, right: pd.Series, *, where: str
) -> tuple[pd.Series, pd.Series]

Bring two time columns to one unit, so they can be merged.

Parameters
NameTypeDescriptionDefault
leftSeriesTime values of the first frame.required
rightSeriesTime values of the second frame.required
wherestrName of the calling function, used in the message.required
Returns
TypeDescription
SeriesBoth Series as datetime64[ns], in the timezone of left when
Seriesboth are tz-aware.
Raises
TypeDescription
ValueErrorWhen one side is tz-aware and the other is naive.

localize_like​

functionsource
localize_like(value: Any, reference: pd.Series) -> pd.Timestamp

Return value as a Timestamp in the timezone of reference.

A naive bound on tz-aware data is read as local time of the data; an aware bound on naive data is converted to UTC and made naive.

Parameters
NameTypeDescriptionDefault
valueAnyA time bound (string, datetime, Timestamp).required
referenceSeriesThe time column the bound is compared with.required
Returns
TypeDescription
TimestampThe bound, comparable with reference.

localize_in​

functionsource
localize_in(value: Any, tz: Any) -> pd.Timestamp

Return value as a Timestamp in tz (naive when tz is None).

The rule of :func:localize_like, for a timezone instead of a column: a naive value is read as wall-clock time in tz (an ambiguous time is read as standard time, a nonexistent one is shifted forward); an aware value is converted. With tz=None an aware value is converted to UTC and made naive.

Parameters
NameTypeDescriptionDefault
valueAnyA time (string, datetime, Timestamp).required
tzAnyTarget timezone, or None for naive.required
Returns
TypeDescription
TimestampThe value as a Timestamp.

to_ns​

functionsource
to_ns(values: pd.Series | pd.Index) -> npt.NDArray[np.int64]

Times as int64 nanoseconds since the epoch.

Works for naive and tz-aware values of any unit: an aware value gives the nanoseconds of its UTC instant, a naive value those of its wall-clock reading. NaT becomes the minimum int64 (numpy's NaT), which sorts first.

Parameters
NameTypeDescriptionDefault
valuesSeries | IndexDatetime Series or Index.required
Returns
TypeDescription
NDArray[int64]One int64 per value, in input order.

ffill_values​

functionsource
ffill_values(series: pd.Series) -> pd.Series

Forward-fill series and keep its dtype.

Series.ffill on an object column infers a narrower dtype for the result, which pandas 2.2 reports as deprecated silent downcasting. This takes every missing value from the last value before it instead and leaves the dtype alone; leading missing values stay missing.

Parameters
NameTypeDescriptionDefault
seriesSeriesValues to fill.required
Returns
TypeDescription
SeriesThe filled Series, same index, name and dtype.

signal_frame_input​

functionsource
signal_frame_input(
*, time_column: str = "time_column", default_time: str = "systime"
) -> Callable[[F], F]

Run a computing classmethod on a normalized copy of its frame.

The first positional argument after cls is copied and passed through :func:~ts_shape.utils.normalize.normalize_signal_frame, so nullable, pyarrow and text-number columns compute like NumPy columns. Use it for functions that compute on the values; functions that return input rows unchanged (filters) keep the caller's dtypes and do not use it.

Parameters
NameTypeDescriptionDefault
time_columnstrName of the keyword that holds the time column.'time_column'
default_timestrTime column when the keyword is not passed.'systime'
Returns
TypeDescription
Callable[[F], F]A decorator for a (cls, dataframe, ...) method.

window_offset​

functionsource
window_offset(window: Any) -> Any

The pandas offset of window, with "D" as a calendar day.

pandas 3 reads "1D" as a calendar day (23 h or 25 h on a DST change); pandas 2 reads it as a fixed 24 h. Window ends are computed the pandas-3 way on both, so a daily window on a DST day has its real length.

Parameters
NameTypeDescriptionDefault
windowAnyOffset string ("1h", "1D", "MS") or offset.required
Returns
NameTypeDescription
AnyA pandas offset; for a day frequency one that adds n calendar
Anydays. On pandas 3 that is to_offset(window) itself (pandas' own
Anycalendar Day, e.g. <3 * Days>); on pandas 2, where Day
Anyis a fixed 24 h Tick, it is pd.DateOffset(days=n). Any other
Anywindow gives to_offset(window) (e.g. <24 * Hours> for
Any"24h"). A Timedelta (or datetime.timedelta /
Anynumpy.timedelta64) window is a fixed duration on both pandas
versionsAnyTimedelta("2D") -> <48 * Hours>.

compact_frame​

functionsource
compact_frame(
dataframe: pd.DataFrame,
*,
uuid_column: str = "uuid",
drop_empty: bool = True
) -> pd.DataFrame

A long-format frame in less memory, same values.

  • the uuid column becomes a category (a few hundred signals repeat over millions of rows);
  • value_integer becomes nullable Int64, value_bool nullable boolean, value_double stays float64;
  • plctime, sequence_number and value_bytes are dropped when they hold no information (all missing, all equal or all zero), and any other column that is entirely missing is dropped too (drop_empty); the uuid and value_* columns are always kept;
  • value_integer is only cast when every value is a whole number.

On a real export this cut the memory of a 6-hour slice from 1,032 MB to 287 MB. Detectors accept the compact frame as it is.

Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format frame.required
uuid_columnstrThe signal column.'uuid'
drop_emptyboolDrop columns without information (see above).True
Returns
TypeDescription
DataFrameA new, compact frame (the input is not changed).