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.

handle multiindex with numeric levels (#5026)

Alexander Kislukhin2cd6f8802c12
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 813e3a1ecb..94859e863f 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -171,14 +171,18 @@ class PandasTableManagerFactory(TableManagerFactory):
LOGGER.info(
"Multi-column indexes are not supported, converting to single index"
)
+ _cols = data_copy.columns
if INDEX_COLUMN_NAME in data_copy.columns:
data_copy.columns = pd.Index(
[INDEX_COLUMN_NAME]
- + [",".join(col) for col in data_copy.columns[1:]]
+ + [
+ ",".join([str(lev) for lev in c])
+ for c in _cols[1:]
+ ]
)
else:
data_copy.columns = pd.Index(
- [",".join(col) for col in data_copy.columns]
+ [",".join([str(lev) for lev in c]) for c in _cols]
)
return data_copy
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 87343e3d2d..4367c3d790 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -254,6 +254,21 @@ class TestPandasTableManager(unittest.TestCase):
{"X": "z", "Y": 3, "a": 3, "b": 6},
]
+ def test_to_json_multi_index_numeric(self) -> None:
+ # MultiIndex with numeric levels
+ data = pd.DataFrame(
+ {
+ "category": list("abab"),
+ "num_col": [0, 0, 1, 1],
+ "str_col": list("aabb"),
+ "val": [1, 2, 3, 4],
+ }
+ )
+ data_pivoted = data.pivot(
+ index="category", columns=["num_col", "str_col"], values="val"
+ )
+ assert PandasTableManagerFactory.create()(data_pivoted) is not None
+
@pytest.mark.xfail(reason="Implementation not yet supported")
def test_to_json_multi_index_unnamed(self) -> None:
data = pd.DataFrame(