Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: polars Array type casting when converting to a csv (#1854)

Myles Scolnick3bcc26ec43be
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 384302cb73..79611adbee 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -37,22 +37,24 @@ class PolarsTableManagerFactory(TableManagerFactory):
# Try to convert columns to json or strings
result = self.data
for column in result.get_columns():
- if column.dtype == pl.Struct:
+ dtype = column.dtype
+ if isinstance(dtype, pl.Struct):
result = result.with_columns(
column.struct.json_encode()
)
- elif column.dtype == pl.List:
+ elif isinstance(dtype, pl.List):
result = result.with_columns(
column.cast(pl.List(pl.Utf8)).list.join(",")
)
- elif column.dtype == pl.Array:
+ elif isinstance(dtype, pl.Array):
result = result.with_columns(
- column.cast(pl.Array(pl.Utf8)).arr.join(",")
+ column.cast(
+ pl.Array(pl.Utf8, shape=dtype.shape)
+ ).arr.join(",")
)
- elif column.dtype == pl.Object:
+ elif isinstance(dtype, pl.Object):
result = result.with_columns(column.cast(str))
- elif column.dtype == pl.Duration:
- dtype = cast(pl.Duration, column.dtype)
+ elif isinstance(dtype, pl.Duration):
if dtype.time_unit == "ns":
result = result.with_columns(
column.dt.total_nanoseconds()
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 076d7288ea..635c91d715 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -106,6 +106,17 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
assert isinstance(data, bytes)
snapshot("polars.csv", data.decode("utf-8"))
+ def test_to_csv_array(self) -> None:
+ import numpy as np
+ import polars as pl
+
+ df = pl.DataFrame(
+ {"a": [np.arange(5) for _ in range(10)]},
+ schema={"a": pl.Array(pl.Int64, 5)},
+ )
+ manager = self.factory.create()(df)
+ assert isinstance(manager.to_csv(), bytes)
+
def test_to_json(self) -> None:
assert isinstance(self.manager.to_json(), bytes)