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.

Exclude index columns for pivot for count/sum agg (#8769)

Shahmir Varqha753f9bf98a12
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
index 5b53b12d26..24feceb012 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
@@ -487,7 +487,9 @@ class NarwhalsTransformHandler(TransformHandler[DataFrame]):
for df_ in dfs:
result = result.join(df_, on=index_columns, how="left")
if transform.aggregation in {"count", "sum"}:
- result = result.select(nw.all().fill_null(0))
+ result = result.with_columns(
+ nw.exclude(*index_columns).fill_null(0)
+ )
return result.sort(by=index_columns)
@staticmethod
diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
index 56a5f1cc1d..0312c6152b 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
@@ -1658,6 +1658,32 @@ class TestTransformHandler:
result, expected, allow_nan_equals_zero=True
)
+ @staticmethod
+ def test_pivot_count_preserves_boolean_index_dtype() -> None:
+ """fill_null(0) on value columns must not alter boolean index dtypes."""
+ import polars as pl
+
+ df = pl.DataFrame(
+ {
+ "category": ["x", "x", "y"],
+ "id": [1, 2, 1],
+ "flag": [True, False, True],
+ "value": [10, 20, 30],
+ }
+ )
+
+ transform = PivotTransform(
+ type=TransformType.PIVOT,
+ column_ids=["category"],
+ index_column_ids=["id", "flag"],
+ value_column_ids=["value"],
+ aggregation="count",
+ )
+
+ result = apply(df, transform)
+ nw_result = nw.from_native(result)
+ assert nw_result.schema["flag"] == nw.Boolean
+
@staticmethod
@pytest.mark.parametrize(
("df", "expected", "expected2"),