Skip to content

Polars

flowcean.polars provides dataframe environments, dataset splitting, time-series transforms, and baseline learners. See environments and transforms for usage concepts.

polars

Attributes

SignalFilterType module-attribute

SignalFilterType = Literal['lowpass', 'highpass']

Classes

DummyLearner

Bases: SupervisedLearner, SupervisedIncrementalLearner

Dummy learner that learns nothing.

This learner is useful for testing purposes.

Methods:
learn
learn(inputs: LazyFrame, outputs: LazyFrame) -> DummyModel
learn_incremental
learn_incremental(inputs: LazyFrame, outputs: LazyFrame) -> DummyModel

DummyModel

DummyModel(output_names: list[str])

Bases: Model

Dummy model that predicts zeros.

This model is useful for testing purposes.

Initialize the model.

Parameters:

Name Type Description Default
output_names list[str]

The names of the output features.

required
Attributes
output_names instance-attribute
output_names = output_names

DataFrame

DataFrame(data: DataFrame | LazyFrame)

Bases: OfflineEnvironment

A dataset environment.

This environment represents static tabular datasets.

Attributes:

Name Type Description
data LazyFrame

The data to represent.

Initialize the dataset environment.

Parameters:

Name Type Description Default
data DataFrame | LazyFrame

The data to represent.

required
Attributes
data instance-attribute
data: LazyFrame
Methods:
to_incremental
to_incremental(batch_size: int = 1) -> StreamingOfflineEnvironment

Convert the DataFrame to an incremental environment.

Parameters:

Name Type Description Default
batch_size int

The size of each batch. Defaults to 1.

1
from_csv classmethod
from_csv(path: str | PathLike[str], separator: str = ',') -> Self

Load a dataset from a CSV file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the CSV file.

required
separator str

Value separator. Defaults to ",".

','
from_json classmethod
from_json(path: str | PathLike[str]) -> Self

Load a dataset from a JSON file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the JSON file.

required
from_parquet classmethod
from_parquet(path: str | PathLike[str]) -> Self

Load a dataset from a Parquet file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the Parquet file.

required
from_yaml classmethod
from_yaml(path: str | Path) -> Self

Load a dataset from a YAML file.

Parameters:

Name Type Description Default
path str | Path

Path to the YAML file.

required
from_uri classmethod
from_uri(uri: str) -> Self

Load a dataset from a URI.

Parameters:

Name Type Description Default
uri str

The URI to load the dataset from.

required
from_rosbag classmethod
from_rosbag(path: str | PathLike[str], topics: dict[str, list[str]], *, message_paths: Iterable[str | PathLike[str]] | None = None, cache: bool = True, cache_path: str | PathLike[str] | None = None) -> Self

Load a dataset from a ROS2 Humble rosbag file.

The structure of the data is inferred from the message definitions. If a message definition is not found in the ROS2 Humble typestore, it is added from the provided paths. Once all the message definitions are added, the data is loaded from the rosbag file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the rosbag.

required
topics dict[str, list[str]]

Dictionary of topics to load (topic: [paths]).

required
message_paths Iterable[str | PathLike[str]] | None

List of paths to additional message definitions.

None
cache bool

Whether to cache the data to a Parquet file.

True
cache_path str | PathLike[str] | None

Path to the cache file. If None, defaults to the same directory as the rosbag file with a .parquet extension.

None

InvalidUriSchemeError

InvalidUriSchemeError(scheme: str)

Bases: Exception

Exception raised when an URI scheme is invalid.

Initialize the InvalidUriSchemeError.

Parameters:

Name Type Description Default
scheme str

Invalid URI scheme.

required

UnsupportedFileTypeError

UnsupportedFileTypeError(suffix: str)

Bases: Exception

Exception raised when a file type is not supported.

Initialize the UnsupportedFileTypeError.

Parameters:

Name Type Description Default
suffix str

File type suffix.

required

DatasetPredictionEnvironment

DatasetPredictionEnvironment(environment: DataFrame, batch_size: int)

Bases: ActiveEnvironment

Dataset prediction environment.

Initialize the dataset prediction environment.

Parameters:

Name Type Description Default
environment DataFrame

The dataset to use for prediction.

required
batch_size int

The batch size of the prediction.

required
Attributes
environment instance-attribute
environment: DataFrame = environment
batch_size instance-attribute
batch_size: int = batch_size
data class-attribute instance-attribute
data: LazyFrame | None = None
slice class-attribute instance-attribute
slice: LazyFrame | None = None
i class-attribute instance-attribute
i: int = 0
Methods:
step
step() -> None
act
act(action: DataFrame) -> None

JoinedOfflineEnvironment

JoinedOfflineEnvironment(environments: Iterable[OfflineEnvironment])

Bases: OfflineEnvironment

Environment that joins multiple offline environments.

Attributes:

Name Type Description
environments Iterable[OfflineEnvironment]

The offline environments to join.

Initialize the joined offline environment.

Parameters:

Name Type Description Default
environments Iterable[OfflineEnvironment]

The offline environments to join.

required
Attributes
environments instance-attribute
environments: Iterable[OfflineEnvironment] = environments

StreamingOfflineEnvironment

StreamingOfflineEnvironment(environment: OfflineEnvironment, batch_size: int, *, size: int | None = None)

Bases: IncrementalEnvironment

Streaming offline environment.

This environment streams data from an offline environment in batches.

Initialize the streaming offline environment.

Parameters:

Name Type Description Default
environment OfflineEnvironment

The offline environment to stream.

required
batch_size int

The batch size of the streaming environment.

required
size int | None

The number of samples in the environment. If provided, the number of steps will be calculated based on this value.

None
Attributes
environment instance-attribute
environment: OfflineEnvironment = environment
batch_size instance-attribute
batch_size: int = batch_size
data class-attribute instance-attribute
data: LazyFrame | None = None
slice class-attribute instance-attribute
slice: LazyFrame | None = None
i class-attribute instance-attribute
i: int = 0
sample_count instance-attribute
sample_count = size
Methods:
step
step() -> None
num_steps
num_steps() -> int | None

TrainTestSplit

TrainTestSplit(ratio: float, *, shuffle: bool = False)

Split data into train and test sets.

Initialize the train-test splitter.

Parameters:

Name Type Description Default
ratio float

The ratio of the data to put in the training set.

required
shuffle bool

Whether to shuffle the data before splitting.

False
Attributes
ratio instance-attribute
ratio = ratio
shuffle instance-attribute
shuffle = shuffle
Methods:
split
split(environment: OfflineEnvironment) -> tuple[DataFrame, DataFrame]

Split the data into train and test sets.

Parameters:

Name Type Description Default
environment OfflineEnvironment

The environment to split.

required

LazyMixin

LazyMixin(**kwargs: Any)

If input is a polars.LazyFrame, collect() it before passing on.

Methods:
prepare
prepare(data: Data) -> Data

SelectMixin

SelectMixin(*, features: Sequence[str] | None = None, **kwargs: Any)

Select only specified columns from DataFrame-like objects.

Attributes
features class-attribute instance-attribute
features: Sequence[str] | None = features
Methods:
prepare
prepare(data: Data) -> Data

Cast

Cast(target_type: PolarsDataType | dict[str, PolarsDataType], *, features: Iterable[str] | None = None)

Bases: Transform

Cast features to a different datatype.

This transform allows to change the datatype of features in a DataFrame. To cast all features to the same datatype, provide a single type as the target_type argument e.g.

transform = Cast(pl.Float64)

By specifying the features keyword argument, only the selected features will be cast e.g.

transform = Cast(pl.Float64, features=["feature_a"])

Lastly, to cast features to different datatypes, provide a dictionary with feature names as keys and target types as values e.g.

transform = Cast(
    {
        "feature_a": pl.Boolean,
        "feature_b": pl.Float64,
    },
)

Initializes the Cast transform.

Parameters:

Name Type Description Default
target_type PolarsDataType | dict[str, PolarsDataType]

Type to which the features will be cast. If a single type is provided, all features or those provided in the features keyword argument will be cast to that specific type. To cast features to different types, provide a dictionary with feature names as keys and target types as values.

required
features Iterable[str] | None

The features to cast. If None all features will be cast. This is the default behaviour.

None
Attributes
target_type instance-attribute
target_type = target_type
features instance-attribute
features = features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Cluster

Cluster(clusterer: Clusterer, *, cluster_feature_name: str = 'cluster_label', features: Iterable[str] | None = None)

Bases: Transform

Cluster data using a clustering algorithm.

This transform allows to cluster data using a specified clustering algorithm. The resulting cluster label is added as a new feature to the DataFrame.

Initializes the Cluster transform.

Parameters:

Name Type Description Default
clusterer Clusterer

The clustering algorithm to use.

required
cluster_feature_name str

The name of the feature to store the cluster labels.

'cluster_label'
features Iterable[str] | None

The features to use for clustering. If None, all features are used.

None
Attributes
clusterer instance-attribute
clusterer = clusterer
cluster_feature_name instance-attribute
cluster_feature_name = cluster_feature_name
features instance-attribute
features = features
Methods:
apply
apply(data: LazyFrame | DataFrame) -> LazyFrame
fit
fit(data: LazyFrame | DataFrame) -> Cluster

DiscreteDerivative

DiscreteDerivative(features: str | Iterable[str], *, method: DiscreteDerivativeKind = 'central', derivative_suffix: str = '_derivative')

Bases: Transform

Calculates the discrete derivative of time series features.

Calculates the discrete derivative of time series features using either forward, backward, or central differences.

Initializes the DiscreteDerivative transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

Features that shall be differentiated. Result features will be named <feature>_derivative.

required
method DiscreteDerivativeKind

Method to use for calculating the derivative. Valid options are "forward", "backward", and "central". Defaults to "central".

'central'
derivative_suffix str

Suffix to append to the feature name for the resulting derivative feature. Defaults to "_derivative".

'_derivative'
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
method instance-attribute
method = method
derivative_suffix instance-attribute
derivative_suffix = derivative_suffix
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Drop

Drop(features: str | Iterable[str], *more_features: str)

Bases: Transform

Drop features from the data.

Initializes the Drop transform.

Attributes
features instance-attribute
features = features
more_features instance-attribute
more_features = more_features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Explode

Explode(features: str | Sequence[str] | None = None, *more_features: str)

Bases: Transform

This wraps the explode method of Polars.

Reference: https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.explode.html#polars.DataFrame.explode If features is None, all columns will be exploded.

Parameters:

Name Type Description Default
features list[str] | None

List of features to explode.

None
Attributes
features instance-attribute
features = features
more_features instance-attribute
more_features = more_features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

ExplodeTimeSeries

ExplodeTimeSeries(features: ColumnNameOrSelector)

Bases: Transform

Transform that explodes nested time series data into individual rows.

Each time series is represented as a list of structs, where each struct contains a timestamp and a value. The value is itself a struct holding multiple feature values at that timestamp. This transform expands the list into separate rows, then unnests the nested structs into columns.

Example

Input DataFrame: ┌─────┬────────────────────────────────────────┐ │ id │ series │ │ --- │ --- │ │ i64 │ list[struct[timestamp: str, value]] │ ├─────┼────────────────────────────────────────┤ │ 1 │ [{t1, {a=1, b=10}}, {t2, {a=2, b=20}}] │ │ 2 │ [{t3, {a=3, b=30}}, {t4, {a=4, b=40}}] │ └─────┴────────────────────────────────────────┘

After applying ExplodeTimeSeries("series"): ┌─────┬────────────┬─────┬─────┐ │ id │ timestamp │ a │ b │ │ --- │ --- │ --- │ --- │ │ i64 │ str │ i64 │ i64 │ ├─────┼────────────┼─────┼─────┤ │ 1 │ t1 │ 1 │ 10 │ │ 1 │ t2 │ 2 │ 20 │ │ 2 │ t3 │ 3 │ 30 │ │ 2 │ t4 │ 4 │ 40 │ └─────┴────────────┴─────┴─────┘

Attributes
features instance-attribute
features: ColumnNameOrSelector = features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

And

And(expressions: str | FilterExpr | Iterable[str | FilterExpr])

Bases: CollectionExpr

Methods:
get
get() -> Expr

CollectionExpr

CollectionExpr(expressions: str | FilterExpr | Iterable[str | FilterExpr])

Bases: FilterExpr

Attributes
expr_collection instance-attribute
expr_collection: Iterable[Expr] = (expression() if isinstance(expression, FilterExpr) else _str_to_pl(expression) for expression in expressions)

Filter

Filter(expression: str | FilterExpr)

Bases: Transform

Filter an environment based on one or multiple expressions.

This transform allows to filter an environment based on or multiple boolean expressions. Assuming the input environment is given by

t N x
1 10 0
2 12 1
3 5 2
4 15 1
5 17 0

The following transformation can be used to filter the environment so that the result contains only records where x=1:

    Filter("x == 1")

The result dataset after applying the transform will be

t N x
2 15 1
4 12 1

To only get records where x=1 and t > 3 the filter expression

Filter(And(["x == 1", "t > 3"]))

can be used.

To filter all records where x=1 and t > 3 or N < 15 use

Filter(And(["x == 1", Or(["t > 3", "N < 15"])]))

Initializes the Filter transform.

Parameters:

Name Type Description Default
expression str | FilterExpr

String or filter expression used to filter the environment. Records that do not match the expression are discarded. Standard comparison and mathematical operations are supported within the expressions. Features can be accessed by there name.

required
Attributes
predicate instance-attribute
predicate: Expr
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

FilterExpr

Bases: Protocol

Expression to be used in a Filter transform.

Methods:
get abstractmethod
get() -> Expr

Get the polars expression for this filter.

Not

Not(expression: str | FilterExpr)

Bases: FilterExpr

Attributes
expression instance-attribute
expression: Expr = expression() if isinstance(expression, FilterExpr) else _str_to_pl(expression)
Methods:
get
get() -> Expr

Or

Or(expressions: str | FilterExpr | Iterable[str | FilterExpr])

Bases: CollectionExpr

Methods:
get
get() -> Expr

First

First(features: str | Iterable[str], *, replace: bool = False)

Bases: Transform

Selects the first time value of a time-series feature.

Initializes the First transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

The features to apply this transform to.

required
replace bool

Whether to replace the original features with the transformed ones. If set to False, the default, the value will be added as a new feature named {feature}_first.

False
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
replace instance-attribute
replace = replace
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

FeatureLengthVaryError

Bases: Exception

Length of a feature varies over different rows.

Flatten

Flatten(features: Iterable[str] | None = None)

Bases: Transform

Flatten all time series in a DataFrame to individual features.

The given DataFrame's time series are converted into individual features, with each time step creating a new feature. This transform will change the order of the columns in the resulting dataset.

For example the dataset

series_data A B
{[0, 0], [1, 1], [2, 2]} 42 43
{[0, 3], [1, 4], [2, 5]} 44 45

gets flattened into the dataset

series_data_0 series_data_1 series_data_2 A B
0 1 2 42 43
3 4 5 42 43

Initialize the flatten transform.

Parameters:

Name Type Description Default
features Iterable[str] | None

The features to flatten. If not provided or set to None, all possible features from the given dataframe will be flattened.

None
Attributes
features instance-attribute
features = features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

NoTimeSeriesFeatureError

Bases: Exception

Feature is no time series.

Lambda

Lambda(fn: Callable[[LazyFrame], LazyFrame])

Bases: Transform

Apply a custom function to the data of an environment.

Initializes the Lambda transform.

Parameters:

Name Type Description Default
fn Callable[[LazyFrame], LazyFrame]

Function handle to be applied to the data.

required
Attributes
fn instance-attribute
fn = fn
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Last

Last(features: str | Iterable[str], *, replace: bool = False)

Bases: Transform

Selects the last time value of a time-series feature.

Initializes the Last transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

The features to apply this transform to.

required
replace bool

Whether to replace the original features with the transformed ones. If set to False, the default, the value will be added as a new feature named {feature}_last.

False
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
replace instance-attribute
replace = replace
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

FeatureNotFoundError

FeatureNotFoundError(feature: str)

Bases: Exception

Feature not found in the DataFrame.

This exception is raised when a feature is not found in the DataFrame.

MatchSamplingRate

MatchSamplingRate(reference_feature_name: str, feature_interpolation_map: dict[str, MatchSamplingRateMethod] | None = None, fill_strategy: FillStrategy = 'both_ways')

Bases: Transform

Matches the sampling rate of all time series in the DataFrame.

Interpolates the time series to match the sampling rate of the reference time series. The feature_interpolation_map parameter is a dictionary that specifies the interpolation method for each feature. The keys are the feature names, and the values are the interpolation methods. The interpolation method can be 'linear' or 'nearest'. If the feature_interpolation_map parameter is not provided, all features except the reference feature will be interpolated using the 'nearest' method. The fill_strategy parameter specifies the strategy to fill missing values after interpolation. The default value is 'both_ways', which means that missing values will be filled using both forward and backward filling. Other options include 'forward', 'backward', 'min', 'max', 'mean', 'zero', and 'one'.The below example shows the usage of a MatchSamplingRate transform in a run.py file. Assuming the loaded data is represented by the table:

| feature_a                   | feature_b                   | const |
| ---                         | ---                         | ---   |
| list[struct[time,struct[]]] | list[struct[time,struct[]]] | int   |
| --------------------------- | --------------------------- | ----- |
| [{12:26:01.0, {1.2}},       | [{12:26:00.0, {1.0}},       | 1     |
|  {12:26:02.0, {2.4}},       |  {12:26:05.0, {2.0}}]       |       |
|  {12:26:03.0, {3.6}},       |                             |       |
|  {12:26:04.0, {4.8}}]       |                             |       |

The following transform can be used to match the sampling rate of the time series feature_b to the sampling rate of the time series feature_a.

    ...
    environment.load()
    data = environment.get_data()
    transform = MatchSamplingRate(
        reference_feature_name="feature_a",
        feature_interpolation_map={
            "feature_b": "linear",
        },
    )
    transformed_data = transform.transform(data)
    ...

The resulting Dataframe after the transform is:

| feature_a                   | feature_b                   | const |
| ---                         | ---                         | ---   |
| list[struct[time,struct[]]] | list[struct[time,struct[]]] | int   |
| --------------------------- | --------------------------- | ----- |
| [{12:26:00.0, {1.2}},       | [{12:26:00.0, {1.2}},       | 1     |
|  {12:26:01.0, {2.4}},       |  {12:26:01.0, {1.4}},       |       |
|  {12:26:02.0, {3.6}},       |  {12:26:02.0, {1.6}},       |       |
|  {12:26:03.0, {4.8}}]       |  {12:26:03.0, {1.8}}]       |       |

Initialize the transform.

Parameters:

Name Type Description Default
reference_feature_name str

Reference timeseries feature.

required
feature_interpolation_map dict[str, MatchSamplingRateMethod] | None

Key-value pairs of the timeseries features that are targeted in interpolation columns and the interpolation method to use. The interpolation method can be 'linear' or 'nearest'.

None
fill_strategy FillStrategy

Strategy to fill missing values after interpolation.

'both_ways'
Attributes
reference_feature_name instance-attribute
reference_feature_name = reference_feature_name
feature_interpolation_map instance-attribute
feature_interpolation_map = feature_interpolation_map
fill_strategy instance-attribute
fill_strategy = fill_strategy
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Transform the input DataFrame.

Parameters:

Name Type Description Default
data LazyFrame

Input DataFrame.

required

Returns:

Type Description
LazyFrame

Transformed DataFrame.

Mean

Mean(features: str | Iterable[str], *, replace: bool = False)

Bases: Transform

Replaces time-series features with their mean value.

Initializes the Mean transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

The feature or features the mean should be calculated for.

required
replace bool

Whether to replace the original features with the transformed ones. If set to False, the default, the value will be added as a new feature named {feature}_mean.

False
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
replace instance-attribute
replace = replace
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Median

Median(features: str | Iterable[str], *, replace: bool = False)

Bases: Transform

Replaces time-series features with their median value.

Initializes the Median transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

The feature or features the median should be calculated for.

required
replace bool

Whether to replace the original features with the transformed ones. If set to False, the default, the value will be added as a new feature named {feature}_median.

False
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
replace instance-attribute
replace = replace
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Mode

Mode(features: str | Iterable[str], *, replace: bool = False)

Bases: Transform

Mode finds the value that appears most often in time-series features.

Initializes the Mode transform.

Parameters:

Name Type Description Default
features str | Iterable[str]

The features to apply this transform to.

required
replace bool

Whether to replace the original features with the transformed ones. If set to False, the default, the value will be added as a new feature named {feature}_mode.

False
Attributes
features instance-attribute
features = [features] if isinstance(features, str) else features
replace instance-attribute
replace = replace
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

OneCold

OneCold(feature_categories: dict[str, list[Any]], *, check_for_missing_categories: bool = False)

Bases: Transform

Transforms integer features into a set of binary one-cold features.

Transforms integer features into a set of binary one-cold features. The original integer features are dropped and are not part of the resulting data frame.

As an example consider the following data

feature
0
1
2
1
5

When the one-cold transformation is applied, the result is as follows

feature_0 feature_1 feature_2 feature_5
0 1 1 1
1 0 1 1
1 1 0 1
1 0 1 1
1 1 1 0

In the default configuration missing categories are ignored. Their respective entries will all be one. If you however want to enforce that each data entry belongs to a certain category, you can set the check_for_missing_categories flag to true when constructing a One-Cold transform. In that case if an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. This however has an impact on the performance and will slow down the transform.

If you want to enable this check, create the transform as follows: python transform = OneCold( feature_categories={ "feature": [0, 1, 2, 5] }, check_for_missing_categories=True )

Initializes the One-Hot transform.

Parameters:

Name Type Description Default
feature_categories dict[str, list[Any]]

Dictionary of features and a list of categorical values to encode for each.

required
check_for_missing_categories bool

If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false.

False
Attributes
feature_category_mapping instance-attribute
feature_category_mapping: dict[str, dict[str, Any]] = {feature: {f'{feature}_{value}': value for value in values} for feature, values in feature_categories.items()}
check_for_missing_categories instance-attribute
check_for_missing_categories: bool = check_for_missing_categories
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Transform data with this one hot transformation.

Transform data with this one hot transformation and return the resulting dataframe.

Parameters:

Name Type Description Default
data LazyFrame

The data to transform.

required

Returns:

Type Description
LazyFrame

The transformed data.

from_dataframe classmethod
from_dataframe(data: DataFrame, features: Iterable[str], *, check_for_missing_categories: bool = False) -> Self

Creates a new one-hot transformation based on sample data.

Parameters:

Name Type Description Default
data DataFrame

A dataframe containing sample data for determining the categories of the transform.

required
features Iterable[str]

Name of the features for which the one hot transformation will determine the categories.

required
check_for_missing_categories bool

If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false.

False

NoCategoriesError

Bases: Exception

NoMatchingCategoryError

Bases: Exception

OneHot

OneHot(feature_categories: dict[str, list[Any]], *, check_for_missing_categories: bool = False)

Bases: Transform

Transforms integer features into a set of binary one-hot features.

Transforms integer features into a set of binary one-hot features. The original integer features are dropped and are not part of the resulting data frame.

As an example consider the following data

feature
0
1
2
1
5

When the one-hot transformation is applied, the result is as follows

feature_0 feature_1 feature_2 feature_5
1 0 0 0
0 1 0 0
0 0 1 0
0 1 0 0
0 0 0 1

Initializes the One-Hot transform.

Parameters:

Name Type Description Default
feature_categories dict[str, list[Any]]

Dictionary of features and a list of categorical values to encode for each.

required
check_for_missing_categories bool

If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false.

False
Attributes
feature_category_mapping instance-attribute
feature_category_mapping: dict[str, dict[str, Any]] = {feature: {f'{feature}_{value}': value for value in values} for feature, values in feature_categories.items()}
check_for_missing_categories instance-attribute
check_for_missing_categories: bool = check_for_missing_categories
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Transform data with this one hot transformation.

Transform data with this one hot transformation and return the resulting dataframe.

Parameters:

Name Type Description Default
data LazyFrame

The data to transform.

required

Returns:

Type Description
LazyFrame

The transformed data.

from_dataframe classmethod
from_dataframe(data: LazyFrame, features: Iterable[str], *, check_for_missing_categories: bool = False) -> Self

Creates a new one-hot transformation based on sample data.

Parameters:

Name Type Description Default
data LazyFrame

A dataframe containing sample data for determining the categories of the transform.

required
features Iterable[str]

Name of the features for which the one hot transformation will determine the categories.

required
check_for_missing_categories bool

If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false.

False

Pad

Pad(length: float, *, features: str | Iterable[str] | None = None)

Bases: Transform

Pad time-series features to the specified length.

Pad time-series features to the specified end-time by holding their last value for one more sample. This is useful for ensuring that all time-series features cover at least a time interval of the specified length. Time-series that are already longer than the specified will not be modified. The resulting features will not be equidistant in time. To achieve equidistant time-series, consider using the Resample transform after padding.

Initializes the Pad transform.

Parameters:

Name Type Description Default
length float

The length (time) to pad the features to. This is the minimum length that the features will have after applying this transform.

required
features str | Iterable[str] | None

The features to apply this transform to. Defaults to None, which will apply the transform to all time-series features.

None
Attributes
length instance-attribute
length = length
features instance-attribute
features = cast('list[str]', [features] if isinstance(features, str) else list(features)) if features is not None else None
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Rename

Rename(mapping: dict[str, str])

Bases: Transform

Rename features in an environment.

Initializes the Rename transform.

Parameters:

Name Type Description Default
mapping dict[str, str]

Key value pairs that map from the old feature name to the new one.

required
Attributes
mapping instance-attribute
mapping = mapping
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Resample

Resample(sampling_rate: float | dict[str, float], *, interpolation_method: InterpolationMethod = 'linear')

Bases: Transform

Resample time series features to a given sampling rate.

Initializes the Resample transform.

Parameters:

Name Type Description Default
sampling_rate float | dict[str, float]

Target sampling rate for time series features. If a float is provided, all possible time series features will be resampled. Alternatively, a dictionary can be provided where the key is the feature and the value is the target sample rate.

required
interpolation_method InterpolationMethod

The interpolation method to use. Supported are "linear" and "cubic", with the default being "linear".

'linear'
Attributes
sampling_rate instance-attribute
sampling_rate = sampling_rate
interpolation_method instance-attribute
interpolation_method = interpolation_method
Methods:
apply
apply(data: LazyFrame) -> LazyFrame
resample_data
resample_data(data: dict[str, list[float]], dt: float) -> Series

ScaleToRange dataclass

ScaleToRange(*, features: list[str] | None = None, lower_range: float = -1.0, upper_range: float = 1.0)

Bases: Invertible, Transform

Scale features to a fixed range using a linear mapping.

A sample \(x\) is scaled as:

\[ z = x \cdot m + b \]

where

  • \(m\) is the scaling factor
  • \(b\) is the offset.

When instantiating this transform directly, the scaling factor \(m\) and offset \(b\) for each feature are calculated during training from the data. To specify the scaling factor \(m\) and offset \(b\) directly, use the from_limits method.

Attributes:

Name Type Description
m dict[str, float] | None

The scaling factor \(m\) of each feature.

b dict[str, float] | None

The offset \(b\) of each feature.

Attributes
features class-attribute instance-attribute
features: list[str] | None = features
m class-attribute instance-attribute
m: dict[str, float] | None = None
b class-attribute instance-attribute
b: dict[str, float] | None = None
lower_range class-attribute instance-attribute
lower_range: float = lower_range
upper_range class-attribute instance-attribute
upper_range: float = upper_range
Methods:
fit
fit(data: LazyFrame) -> Self
fit_incremental
fit_incremental(data: Data) -> Self
apply
apply(data: LazyFrame) -> LazyFrame
inverse
inverse() -> Transform
from_limits classmethod
from_limits(feature_limits: dict[str, tuple[float, float]], *, lower_range: float = -1.0, upper_range: float = 1.0) -> Self

Creates a new ScaleToRange transform based on the given limits.

Parameters:

Name Type Description Default
feature_limits dict[str, tuple[float, float]]

A dictionary mapping each features name to its (min_value, max_value) tuple.

required
lower_range float

The lower bound of the range to scale to.

-1.0
upper_range float

The upper bound of the range to scale to.

1.0

Select

Select(features: IntoExpr | Iterable[IntoExpr])

Bases: Transform

Selects a subset of features from the data.

Initializes the Select transform.

Parameters:

Name Type Description Default
features IntoExpr | Iterable[IntoExpr]

The features to select. Treats the selection as a parameter to polars select method. You can use regular expressions by wrapping the argument by ^ and $.

required
Attributes
features instance-attribute
features = features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

SignalFilter

SignalFilter(features: Iterable[str], filter_type: SignalFilterType, filter_frequency: float, *, order: int = 5)

Bases: Transform

Applies a Butterworth filter to time series features.

Applies a Butterworth lowpass or highpass filter to time series features. For this transform to work, the time series must already have a uniform sampling rate. Use a `Resample' transform to uniformly sample the points of a time series.

Initializes the Filter transform.

Parameters:

Name Type Description Default
features Iterable[str]

Features that shall be filtered.

required
filter_type SignalFilterType

Type of the filter to apply. Valid options are "lowpass" and "highpass".

required
filter_frequency float

Characteristic frequency of the filter in Hz. For high- and lowpass this is the cutoff frequency.

required
order int

Order of the Butterworth filter to uses. Defaults to 5.

5
Attributes
features instance-attribute
features = features
filter_type instance-attribute
filter_type = filter_type
frequency instance-attribute
frequency = filter_frequency
order instance-attribute
order = order
Methods:
apply
apply(data: LazyFrame) -> LazyFrame
filter_data
filter_data(data: dict[str, list[float]]) -> Series

SliceTimeSeries

SliceTimeSeries(time_series: str, slice_points: str)

Bases: Transform

Slices a time series at given slice points.

The transform takes two columns as input: 'time_series' and 'slice_points.' The 'time_series' column is sliced at the points specified by the 'time' entry of the 'slice_points' column. The result is a new time series column where each entry contains only the values from the original time series that fall between the specified slice points.

Suppose you have a dataframe with a single line entry as follows:

time_series slice_points
[(00:00:03, 1), [(00:00:05, 0),
(00:00:04, 2), (00:00:08, 1)]
(00:00:06, 7),
(00:00:09, 0)]

Applying the slice time series transform results in a multi-line dataframe, where each line corresponds to a slice point:

time_series slice_points
[(00:00:03, 1), [(00:00:05, 0)]
(00:00:04, 2)]
[(00:00:06, 7)] [(00:00:08, 1)]

The transform operates line-wise, meaning that each line in the input dataframe is processed independently. The resulting dataframe will have multiple lines depending on the number of slice points specified in each line.

Initialize the SliceTimeSeries transform.

Parameters:

Name Type Description Default
time_series str

the time series column to slice.

required
slice_points str

the column that specifies the slice points.

required
Attributes
time_series instance-attribute
time_series = time_series
slice_points instance-attribute
slice_points = slice_points
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

SlidingWindow

SlidingWindow(window_size: int)

Bases: Transform

Transforms the data with a sliding window.

The sliding window transform transforms the data by creating a sliding window over the row dimension. The data is then transformed by creating a new column for each column in the original data. The new columns are named by appending the index of the row in the sliding window to the original column name. As an example, consider the following data:

x y z
1 10 100
2 20 200
3 30 300
4 40 400
5 50 500

If we apply a sliding window with a window size of 3, we get the following

x_0 y_0 z_0 x_1 y_1 z_1 x_2 y_2 z_2
1 10 100 2 20 200 3 30 300
2 20 200 3 30 300 4 40 400
3 30 300 4 40 400 5 50 500

Parameters:

Name Type Description Default
window_size int

size of the sliding window.

required
Attributes
window_size instance-attribute
window_size = window_size
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

TimeSeriesSlidingWindow

TimeSeriesSlidingWindow(window_size: int, *, features: str | Iterable[str] | None = None, stride: int = 1, rechunk: bool = True)

Bases: Transform

Convert single large time series into a set of smaller sub-series.

Applies a sliding window to each individual time series sample of all or selected time series features while leaving other features unchanged. As a result, the resulting data frame will contain multiple samples for each original sample, where each sample is a sub-series of the original time series. The number of features (columns) will remain the same. For this transform to work, all selected time series features of a sample must have the same time vector. Use a MatchSamplingRate or Resample transform to ensure this is the case.

Initializes the TimeSeriesSlidingWindow transform.

Parameters:

Name Type Description Default
window_size int

The size of the sliding window.

required
features str | Iterable[str] | None

The features to apply the sliding window to. If None, all time series features are selected.

None
stride int

The stride of the sliding window.

1
rechunk bool

Whether to rechunk the data after applying the transform. Rechunking improves performance of subsequent operations, but increases memory usage and may slow down the initial operation.

True
Attributes
window_size instance-attribute
window_size = window_size
features instance-attribute
features = features
stride instance-attribute
stride = stride
rechunk instance-attribute
rechunk = rechunk
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Standardize dataclass

Standardize(mean: dict[str, float] | None = None, std: dict[str, float] | None = None)

Bases: Invertible, Transform

Standardize features by removing the mean and scaling to unit variance.

A sample \(x\) is standardized as:

\[ z = \frac{(x - \mu)}{\sigma} \]

where

  • \(\mu\) is the mean of the samples
  • \(\sigma\) is the standard deviation of the samples.

Attributes:

Name Type Description
mean dict[str, float] | None

The mean \(\mu\) of each feature.

std dict[str, float] | None

The standard deviation \(\sigma\) of each feature.

Attributes
mean class-attribute instance-attribute
mean: dict[str, float] | None = None
std class-attribute instance-attribute
std: dict[str, float] | None = None
Methods:
fit
fit(data: LazyFrame) -> Self
fit_incremental
fit_incremental(data: Data) -> Self
apply
apply(data: LazyFrame) -> LazyFrame
inverse
inverse() -> Transform

TimeWindow

TimeWindow(*, features: Iterable[str] | None = None, time_start: float = 0.0, time_end: float = inf)

Bases: Transform

Limit time series to a certain time window.

Initializes the TimeWindow transform.

Parameters:

Name Type Description Default
features Iterable[str] | None

The features to apply this transformation to. If None, all applicable features will be affected.

None
time_start float

Window start time. Defaults to zero. All data before this time will be removed from the time series when applying the transform.

0.0
time_end float

Window end time. Defaults to infinite. All data after this time will be removed from the time series when applying the transform.

inf
Attributes
features instance-attribute
features = features
t_start instance-attribute
t_start = time_start
t_end instance-attribute
t_end = time_end
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

ToTimeSeries

ToTimeSeries(time_feature: str | dict[str, str])

Bases: Transform

Attributes
time_feature instance-attribute
time_feature: str | dict[str, str] = time_feature
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Unnest

Unnest(features: ColumnNameOrSelector | Collection[ColumnNameOrSelector])

Bases: Transform

Decompose struct columns into separate columns for each field.

Example:

data_frame = pl.Series(
    "c",
    [
        {"a": 1, "t": 1},
        {"a": 4, "t": 2},
        {"a": 7, "t": 3},
        {"a": 10, "t": 4},
        {"a": 15, "t": 5},
    ],
).to_frame()
The transformed_data will be:
pl.DataFrame(
    {
        "a": [1, 4, 7, 10, 15],
        "t": [1, 2, 3, 4, 5],
    },
)
.

Initializes the Unnest transform.

Parameters:

Name Type Description Default
features ColumnNameOrSelector | Collection[ColumnNameOrSelector]

The features to unnest. Treats the selection as a parameter to polars unnest method. You can use regular expressions by wrapping the argument by ^ and $.

required
Attributes
features instance-attribute
features = features
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

ZeroOrderHold

ZeroOrderHold(features: list[str], name: str = 'aligned', *, drop: bool = True)

Bases: Transform

Aligns multiple time series features using zero-order-hold.

Initialize the ZeroOrderHoldMatching transform.

Parameters:

Name Type Description Default
features list[str]

List of topics to align.

required
name str

Name of the output time series feature.

'aligned'
drop bool

Whether to drop the original features after alignment.

True
Attributes
features instance-attribute
features = features
name instance-attribute
name = name
drop instance-attribute
drop = drop
Methods:
apply
apply(data: LazyFrame) -> LazyFrame

Functions:

collect

collect(environment: Iterable[LazyFrame] | Collection[LazyFrame], n: int | None = None, *, progress_bar: bool | dict[str, Any] = True) -> DataFrame

Collect data from an environment.

Parameters:

Name Type Description Default
environment Iterable[LazyFrame] | Collection[LazyFrame]

The environment to collect data from.

required
n int | None

Number of samples to collect. If None, all samples are collected.

None
progress_bar bool | dict[str, Any]

Whether to show a progress bar. If a dictionary is provided, it will be passed to the progress bar.

True

Returns:

Type Description
DataFrame

The collected dataset.

is_timeseries_feature

is_timeseries_feature(target: DataFrame | LazyFrame | Schema, name: str) -> bool

Check if the given column is a time series feature.

A time series feature contains a list of structs with fields time and value.

Parameters:

Name Type Description Default
target DataFrame | LazyFrame | Schema

The LazyFrame, DataFrame or schema to check.

required
name str

The column to check.

required

Returns:

Type Description
bool

True if the column is a time series feature, False otherwise.