Skip to main content

A package for converting time series data from e.g. electronic health records into wide format data.

Project description

Timeseriesflattener

github actions docs github actions pytest python versions Code style: black

PyPI version status

Time series from e.g. electronic health records often have a large number of variables, are sampled at irregular intervals and tend to have a large number of missing values. Before this type of data can be used for prediction modelling with machine learning methods such as logistic regression or XGBoost, the data needs to be reshaped.

In essence, the time series need to be flattened so that each prediction time is represented by a set of predictor values and an outcome value. These predictor values can be constructed by aggregating the preceding values in the time series within a certain time window.

timeseriesflattener aims to simplify this process by providing an easy-to-use and fully-specified pipeline for flattening complex time series.

🔧 Installation

To get started using timeseriesflattener simply install it using pip by running the following line in your terminal:

pip install timeseriesflattener

⚡ Quick start

import numpy as np
import pandas as pd

if __name__ == "__main__":

    # Load a dataframe with times you wish to make a prediction
    prediction_times_df = pd.DataFrame(
        {
            "id": [1, 1, 2],
            "date": ["2020-01-01", "2020-02-01", "2020-02-01"],
        },
    )
    # Load a dataframe with raw values you wish to aggregate as predictors
    predictor_df = pd.DataFrame(
        {
            "id": [1, 1, 1, 2],
            "date": [
                "2020-01-15",
                "2019-12-10",
                "2019-12-15",
                "2020-01-02",
            ],
            "value": [1, 2, 3, 4],
        },
    )
    # Load a dataframe specifying when the outcome occurs
    outcome_df = pd.DataFrame({"id": [1], "date": ["2020-03-01"], "value": [1]})

    # Specify how to aggregate the predictors and define the outcome
    from timeseriesflattener.feature_spec_objects import OutcomeSpec, PredictorSpec
    from timeseriesflattener.resolve_multiple_functions import maximum, mean

    predictor_spec = PredictorSpec(
        values_df=predictor_df,
        lookbehind_days=30,
        fallback=np.nan,
        entity_id_col_name="id",
        resolve_multiple_fn=mean,
        feature_name="test_feature",
    )
    outcome_spec = OutcomeSpec(
        values_df=outcome_df,
        lookahead_days=31,
        fallback=0,
        entity_id_col_name="id",
        resolve_multiple_fn=maximum,
        feature_name="test_outcome",
        incident=False,
    )

    # Instantiate TimeseriesFlattener and add the specifications
    from timeseriesflattener import TimeseriesFlattener

    ts_flattener = TimeseriesFlattener(
        prediction_times_df=prediction_times_df,
        entity_id_col_name="id",
        timestamp_col_name="date",
        n_workers=1,
        drop_pred_times_with_insufficient_look_distance=False,
    )
    ts_flattener.add_spec([predictor_spec, outcome_spec])
    df = ts_flattener.get_df()
    df

Output:

id date prediction_time_uuid pred_test_feature_within_30_days_mean_fallback_nan outc_test_outcome_within_31_days_maximum_fallback_0_dichotomous
0 1 2020-01-01 00:00:00 1-2020-01-01-00-00-00 2.5 0
1 1 2020-02-01 00:00:00 1-2020-02-01-00-00-00 1 1
2 2 2020-02-01 00:00:00 2-2020-02-01-00-00-00 4 0

📖 Documentation

Documentation
🎓 Tutorial Simple and advanced tutorials to get you started using timeseriesflattener
🎛 General docs The detailed reference for timeseriesflattener's API.
🙋 FAQ Frequently asked question
🗺️ Roadmap Kanban board for the roadmap for the project

💬 Where to ask questions

Type
🚨 Bug Reports GitHub Issue Tracker
🎁 Feature Requests & Ideas GitHub Issue Tracker
👩‍💻 Usage Questions GitHub Discussions
🗯 General Discussion GitHub Discussions

🎓 Projects

PSYCOP projects which use timeseriesflattener. Note that some of these projects have yet to be published and are thus private.

Project Publications
Type 2 Diabetes Prediction of type 2 diabetes among patients with visits to psychiatric hospital departments
Cancer Prediction of Cancer among patients with visits to psychiatric hospital departments
COPD Prediction of Chronic obstructive pulmonary disease (COPD) among patients with visits to psychiatric hospital departments
Forced admissions Prediction of forced admissions of patients to the psychiatric hospital departments. Encompasses two separate projects: 1. Prediciting at time of discharge for inpatient admissions. 2. Predicting day before outpatient admissions.
Coercion Prediction of coercion among patients admittied to the hospital psychiatric department. Encompasses predicting mechanical restraint, sedative medication and manual restraint 48 hours before coercion occurs.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

timeseriesflattener-0.25.1.tar.gz (5.4 MB view details)

Uploaded Source

Built Distribution

timeseriesflattener-0.25.1-py3-none-any.whl (37.7 kB view details)

Uploaded Python 3

File details

Details for the file timeseriesflattener-0.25.1.tar.gz.

File metadata

  • Download URL: timeseriesflattener-0.25.1.tar.gz
  • Upload date:
  • Size: 5.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.9.6 readme-renderer/37.3 requests/2.29.0 requests-toolbelt/1.0.0 urllib3/1.26.15 tqdm/4.65.0 importlib-metadata/6.6.0 keyring/23.13.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.11

File hashes

Hashes for timeseriesflattener-0.25.1.tar.gz
Algorithm Hash digest
SHA256 a481cdaa1be9a208cd6a65e1e5397fa7913088112cc075e60eddd85ded54084f
MD5 be502e70f570db389e3844fae3b90666
BLAKE2b-256 3e6bda56610431e5bf44ff8a9a824b16bd6768a5b622dd0b0874d42013a1bd16

See more details on using hashes here.

File details

Details for the file timeseriesflattener-0.25.1-py3-none-any.whl.

File metadata

  • Download URL: timeseriesflattener-0.25.1-py3-none-any.whl
  • Upload date:
  • Size: 37.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.9.6 readme-renderer/37.3 requests/2.29.0 requests-toolbelt/1.0.0 urllib3/1.26.15 tqdm/4.65.0 importlib-metadata/6.6.0 keyring/23.13.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.11

File hashes

Hashes for timeseriesflattener-0.25.1-py3-none-any.whl
Algorithm Hash digest
SHA256 125f32fefd44701d89516ec1b766412643a50be0489097daa05a37df98cf948d
MD5 d516b0de7cefe513481d902c988dab3a
BLAKE2b-256 128649a708a839e082177ff80a3efd939d0631767b495e598d116b497f774e5e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page