Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Polars and other dataframes #482

Merged
merged 4 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion chainladder/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import pandas as pd
from packaging import version

import numpy as np
from chainladder.utils.cupy import cp
from chainladder.utils.sparse import sp
Expand Down Expand Up @@ -402,7 +404,30 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
return obj
else:
raise NotImplementedError()


def _interchange_dataframe(self, data):
"""
Convert an object supporting the __dataframe__ protocol to a pandas DataFrame.
Requires pandas version > 1.5.2.

Parameters
----------
data :
Dataframe object supporting the __dataframe__ protocol.
Returns
-------
out: pd.DataFrame
A pandas DataFrame.
"""
# Check if pandas version is greater than 1.5.2
if version.parse(pd.__version__) >= version.parse("1.5.2"):
return pd.api.interchange.from_dataframe(data)

else:
# Raise an error prompting the user to upgrade pandas
raise NotImplementedError("Your version of pandas does not support the DataFrame interchange API. "
"Please upgrade pandas to a version greater than 1.5.2 to use this feature.")

def __array_function__(self, func, types, args, kwargs):
from chainladder.utils.utility_functions import concat

Expand Down
36 changes: 36 additions & 0 deletions chainladder/core/tests/test_triangle.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import chainladder as cl
import pandas as pd
import polars as pl
import numpy as np
import copy
import pytest
Expand Down Expand Up @@ -745,6 +746,9 @@ def test_halfyear_development():
["2012-01-01", "2013-12-31", "incurred", 200.0],
]

df_polars = pl.DataFrame(data)
df_polars.columns = ["origin", "val_date", "idx", "value"]

assert (
type(
cl.Triangle(
Expand All @@ -757,3 +761,35 @@ def test_halfyear_development():
)
)
) == cl.Triangle

assert (
type(
cl.Triangle(
data=df_polars,
index="idx",
columns="value",
origin="origin",
development="val_date",
cumulative=True,
)
)
) == cl.Triangle

assert (
cl.Triangle(
data=pd.DataFrame(data, columns=["origin", "val_date", "idx", "value"]),
index="idx",
columns="value",
origin="origin",
development="val_date",
cumulative=True,
) ==
cl.Triangle(
data=df_polars,
index="idx",
columns="value",
origin="origin",
development="val_date",
cumulative=True,
)
)
6 changes: 4 additions & 2 deletions chainladder/core/triangle.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ def __init__(
):
if data is None:
return

elif not isinstance(data, pd.DataFrame) and hasattr(data, "__dataframe__"):
data = self._interchange_dataframe(data)

index, columns, origin, development = self._input_validation(
data, index, columns, origin, development
)
Expand Down Expand Up @@ -270,7 +272,7 @@ def __init__(
self.ddims = obj.ddims
self.values = obj.values
self.valuation_date = pd.Timestamp(options.ULT_VAL)

@staticmethod
def _split_ult(data, index, columns, origin, development):
"""Deal with triangles with ultimate values"""
Expand Down
1 change: 1 addition & 0 deletions ci/environment-latest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ channels:

dependencies:
- conda-forge::pandas>=2.0
- polars
- scikit-learn>=0.23
- sparse>=0.9
- numba
Expand Down
1 change: 1 addition & 0 deletions ci/environment-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ channels:

dependencies:
- pandas>=0.23
- polars>=0.16.2
- scikit-learn>=0.23
- sparse>=0.9
- numba
Expand Down
1 change: 1 addition & 0 deletions environment-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies:
- ipykernel

- pandas
- polars
- scikit-learn
- sparse
- numba
Expand Down
1 change: 1 addition & 0 deletions environment-docs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dependencies:
- git

- pandas
- polars
- scikit-learn
- sparse
- numba
Expand Down
Loading