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

Add support for serializing polars DataFrame #7475

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
31 changes: 30 additions & 1 deletion panel/io/datamodel.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import sys
import weakref

from functools import partial
from typing import Any

import bokeh
import bokeh.core.properties as bp
Expand Down Expand Up @@ -34,6 +36,26 @@ def validate(self, value, detail=True):
raise ValueError(msg)


class PolarsDataFrame(bokeh.core.property.bases.Property):
""" Accept Polars DataFrame values.

This property only exists to support type validation, e.g. for "accepts"
clauses. It is not serializable itself, and is not useful to add to
Bokeh models directly.

"""

def validate(self, value: Any, detail: bool = True) -> None:
super().validate(value, detail)

import polars as pl
if isinstance(value, (pl.DataFrame, pl.LazyFrame)):
return

msg = "" if not detail else f"expected Pandas DataFrame, got {value!r}"
raise ValueError(msg)


class ParameterizedList(bokeh.core.property.bases.Property):
""" Accept a list of Parameterized objects.

Expand Down Expand Up @@ -87,6 +109,13 @@ def bytes_param(p, kwargs):
kwargs['default'] = None
return bp.Nullable(bp.Bytes, **kwargs)

def df_to_dict(df):
if 'polars' in sys.modules:
import polars as pl
if isinstance(df, (pl.LazyFrame, pl.DataFrame)):
philippjfr marked this conversation as resolved.
Show resolved Hide resolved
df = df.to_pandas()
philippjfr marked this conversation as resolved.
Show resolved Hide resolved
return ColumnDataSource._data_from_df(df)

PARAM_MAPPING = {
pm.Array: lambda p, kwargs: bp.Array(bp.Any, **kwargs),
pm.Boolean: lambda p, kwargs: bp.Bool(**kwargs),
Expand All @@ -97,7 +126,7 @@ def bytes_param(p, kwargs):
pm.Color: color_param_to_ppt,
pm.DataFrame: lambda p, kwargs: (
bp.ColumnData(bp.Any, bp.Seq(bp.Any), **kwargs),
[(bp.PandasDataFrame, lambda x: ColumnDataSource._data_from_df(x))]
[(bp.PandasDataFrame, df_to_dict), (PolarsDataFrame, df_to_dict)]
),
pm.DateRange: lambda p, kwargs: bp.Tuple(bp.Datetime, bp.Datetime, **kwargs),
pm.Date: lambda p, kwargs: bp.Datetime(**kwargs),
Expand Down
Loading