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

improvement: handle pl.Duration #3274

Merged
merged 2 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
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
16 changes: 16 additions & 0 deletions marimo/_plugins/ui/_impl/tables/narwhals_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ def get_field_type(
return ("integer", dtype_string)
elif is_narwhals_temporal_type(dtype):
return ("date", dtype_string)
elif dtype == nw.Duration:
return ("number", dtype_string)
elif dtype.is_numeric():
return ("number", dtype_string)
else:
Expand Down Expand Up @@ -147,6 +149,7 @@ def search(self, query: str) -> TableManager[Any]:
elif (
dtype.is_numeric()
or is_narwhals_temporal_type(dtype)
or dtype == nw.Duration
or dtype == nw.Boolean
):
expressions.append(
Expand Down Expand Up @@ -212,6 +215,19 @@ def _get_summary_internal(self, column: str) -> ColumnSummary:
p75=col.quantile(0.75, interpolation="nearest"),
p95=col.quantile(0.95, interpolation="nearest"),
)
if col.dtype == nw.Duration:
unit_map = {
"ms": col.dt.total_milliseconds,
"ns": col.dt.total_nanoseconds,
"us": col.dt.total_microseconds,
}
return ColumnSummary(
total=total,
nulls=col.null_count(),
min=str(unit_map["us"]().min()) + "μs",
max=str(unit_map["us"]().max()) + "μs",
mean=str(unit_map["us"]().mean()) + "μs",
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it might be worth factoring out the total_* call, so it doesn't get recalculated?

            duration = unit_map["us"]()
            return ColumnSummary(
                total=total,
                nulls=col.null_count(),
                min=str(duration.min()) + "μs",
                max=str(duration.max()) + "μs",
                mean=str(duration.mean()) + "μs",
            )

if (
col.dtype == nw.List
or col.dtype == nw.Struct
Expand Down
23 changes: 10 additions & 13 deletions marimo/_plugins/ui/_impl/tables/polars_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,14 @@ def to_csv(
)
)
elif isinstance(dtype, pl.Duration):
if dtype.time_unit == "ms":
result = result.with_columns(
column.dt.total_milliseconds()
)

elif dtype.time_unit == "ns":
result = result.with_columns(
column.dt.total_nanoseconds()
)
elif dtype.time_unit == "us":
result = result.with_columns(
column.dt.total_microseconds()
)
unit_map = {
"ms": column.dt.total_milliseconds,
"ns": column.dt.total_nanoseconds,
"us": column.dt.total_microseconds,
}
if dtype.time_unit in unit_map:
method = unit_map[dtype.time_unit]
result = result.with_columns(method())
return result.write_csv().encode("utf-8")

def to_json(self) -> bytes:
Expand Down Expand Up @@ -198,6 +193,8 @@ def get_field_type(
return ("date", dtype_string)
elif dtype == pl.Time:
return ("time", dtype_string)
elif dtype == pl.Duration:
return ("number", dtype_string)
elif dtype == pl.Datetime:
return ("datetime", dtype_string)
elif dtype.is_temporal():
Expand Down
57 changes: 57 additions & 0 deletions marimo/_smoke_tests/tables/polars_duration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import marimo

__generated_with = "0.10.6"
app = marimo.App(width="medium")


@app.cell
def _():
import marimo as mo
import polars as pl
return mo, pl


@app.cell
def _(mo):
mo.md(r"""## Polars""")
return


@app.cell
def _(pl):
df = pl.read_csv(
"https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/co2-concentration.csv"
)
df = df.with_columns(
pl.col("CO2").cast(pl.Duration),
)
df
return (df,)


@app.cell
def _(df, mo):
mo.plain(df)
return


@app.cell
def _(mo):
mo.md(r"""## Pandas""")
return


@app.cell
def _(df):
df.to_pandas()
return


@app.cell
def _(df, mo):
mo.plain(df.to_pandas())
return


if __name__ == "__main__":
app.run()
6 changes: 2 additions & 4 deletions marimo/_utils/narwhals_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,11 @@ def is_narwhals_integer_type(

def is_narwhals_temporal_type(
dtype: Any,
) -> TypeGuard[nw.Datetime | nw.Date | nw.Duration | nw.Duration]:
) -> TypeGuard[nw.Datetime | nw.Date]:
"""
Check if the given dtype is temporal type.
"""
return bool(
dtype == nw.Datetime or dtype == nw.Date or dtype == nw.Duration
)
return bool(dtype == nw.Datetime or dtype == nw.Date)


def is_narwhals_string_type(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
["set", ["unknown", "Object"]],
["imaginary", ["unknown", "Object"]],
["time", ["unknown", "Unknown"]],
["duration", ["date", "Duration(time_unit='us')"]],
["duration", ["number", "Duration(time_unit='us')"]],
["mixed_list", ["unknown", "List(String)"]]
]
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
["set", ["unknown", "object"]],
["imaginary", ["unknown", "object"]],
["time", ["time", "Time"]],
["duration", ["datetime", "duration[\u03bcs]"]],
["duration", ["number", "duration[\u03bcs]"]],
["mixed_list", ["unknown", "list[str]"]]
]
1 change: 1 addition & 0 deletions tests/_utils/test_narwhals_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ def test_narwhals_type_checks():
assert is_narwhals_temporal_type(nw.Datetime)
assert is_narwhals_temporal_type(nw.Date)
assert not is_narwhals_temporal_type(nw.Int64)
assert not is_narwhals_temporal_type(nw.Duration)

assert is_narwhals_string_type(nw.String)
assert is_narwhals_string_type(nw.Categorical)
Expand Down
Loading