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: pandas multi-idx col names (#4386)

Shahmir Varqhab5aa0cb85684
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 6ffc1e8cf1..2a364e7cad 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -14,6 +14,7 @@ from marimo._plugins.ui._impl.tables.format import (
format_value,
)
from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
+from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
TableManager,
@@ -36,17 +37,8 @@ class PandasTableManagerFactory(TableManagerFactory):
type = "pandas"
def __init__(self, data: pd.DataFrame) -> None:
- if isinstance(data.columns, pd.MultiIndex):
- LOGGER.debug(
- "Multicolumn indexes aren't supported, converting to single index"
- )
- single_col_names = [
- " x ".join(col) for col in data.columns
- ]
- data.columns = pd.Index(single_col_names)
-
- self._original_data = data
- super().__init__(nw.from_native(data))
+ self._original_data = self._handle_multi_col_indexes(data)
+ super().__init__(nw.from_native(self._original_data))
@cached_property
def schema(self) -> pd.Series[Any]:
@@ -108,7 +100,7 @@ class PandasTableManagerFactory(TableManagerFactory):
)
return result.to_json(orient="records").encode("utf-8")
- # Flatten indexes
+ # Flatten row multi-index
if isinstance(result.index, pd.MultiIndex) or (
isinstance(result.index, pd.Index)
and not isinstance(result.index, pd.RangeIndex)
@@ -154,6 +146,36 @@ class PandasTableManagerFactory(TableManagerFactory):
)
return PandasTableManager(_data)
+ def _handle_multi_col_indexes(
+ self, data: pd.DataFrame
+ ) -> pd.DataFrame:
+ is_multi_col_index = isinstance(data.columns, pd.MultiIndex)
+ # When in a table with selection, narwhals will convert the columns to a tuple
+ is_multi_col_table = (
+ INDEX_COLUMN_NAME in data.columns
+ and len(data.columns) > 1
+ and any(isinstance(col, tuple) for col in data.columns)
+ )
+
+ # Convert multi-index or tuple columns to comma-separated strings
+ if is_multi_col_index or is_multi_col_table:
+ data_copy = data.copy()
+ LOGGER.info(
+ "Multi-column indexes are not supported, converting to single index"
+ )
+ 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:]]
+ )
+ else:
+ data_copy.columns = pd.Index(
+ [",".join(col) for col in data_copy.columns]
+ )
+ return data_copy
+
+ return data
+
# We override the default implementation to use pandas
# headers
def get_row_headers(
diff --git a/marimo/_smoke_tests/tables/pandas_multi_idx.py b/marimo/_smoke_tests/tables/pandas_multi_idx.py
index 503f4b89ff..1065cb6199 100644
--- a/marimo/_smoke_tests/tables/pandas_multi_idx.py
+++ b/marimo/_smoke_tests/tables/pandas_multi_idx.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.11.20"
+__generated_with = "0.12.4"
app = marimo.App(width="medium")
@@ -38,16 +38,22 @@ def _(pd):
@app.cell
-def _(pd):
+def _(mo, pd):
cols = pd.MultiIndex.from_arrays(
[["basic_amt"] * 2, ["NSW", "QLD"]], names=[None, "Faculty"]
)
idx = pd.Index(["All", "Full"])
column_multi_idx = pd.DataFrame([(1, 1), (0, 1)], index=idx, columns=cols)
- column_multi_idx
+ mo.ui.table(column_multi_idx)
return cols, column_multi_idx, idx
+def _(column_multi_idx):
+ print("Raw data:\n", column_multi_idx)
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 8da2b368dd..d9d186fb04 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -275,8 +275,8 @@ class TestPandasTableManager(unittest.TestCase):
json_data = self.factory_create_json_from_df(data)
assert json_data == [
- {"": "All", "basic_amt x NSW": 1, "basic_amt x QLD": 1},
- {"": "Full", "basic_amt x NSW": 0, "basic_amt x QLD": 1},
+ {"": "All", "basic_amt,NSW": 1, "basic_amt,QLD": 1},
+ {"": "Full", "basic_amt,NSW": 0, "basic_amt,QLD": 1},
]
def test_complex_data_field_types(self) -> None:
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 4b686a971b..8e9e4d9cc6 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -16,6 +16,7 @@ from marimo._plugins.ui._impl.table import (
SortArgs,
)
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
+from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
from marimo._plugins.ui._impl.tables.table_manager import TableCell
from marimo._plugins.ui._impl.utils.dataframe import TableData
from marimo._runtime.functions import EmptyArgs
@@ -1436,3 +1437,53 @@ def test_cell_search_df_styles_sorted():
"4": {"column_0": {"backgroundColor": "green"}},
"5": {"column_0": {"backgroundColor": "green"}},
}
+
+
+ not DependencyManager.pandas.has(),
+ reason="Pandas not installed, only pandas has multi-col idx",
+)
+def test_json_multi_col_idx_table() -> None:
+ import pandas as pd
+
+ cols = pd.MultiIndex.from_arrays(
+ [["basic_amt"] * 2, ["NSW", "QLD"]], names=[None, "Faculty"]
+ )
+ idx = pd.Index(["All", "Full"])
+ data = pd.DataFrame([(1, 1), (0, 1)], index=idx, columns=cols)
+ table = ui.table(data)
+
+ json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ assert json_data == [
+ {
+ "": "All",
+ INDEX_COLUMN_NAME: 0,
+ "basic_amt,NSW": 1,
+ "basic_amt,QLD": 1,
+ },
+ {
+ "": "Full",
+ INDEX_COLUMN_NAME: 1,
+ "basic_amt,NSW": 0,
+ "basic_amt,QLD": 1,
+ },
+ ]
+
+ # If col name looks like a tuple
+ df = pd.DataFrame(
+ {
+ "('basic_amt', 'NSW')": [1],
+ "('basic_amt', 'QLD')": [2],
+ }
+ )
+ table = ui.table(df)
+ json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ assert json_data == [
+ {
+ INDEX_COLUMN_NAME: 0,
+ "('basic_amt', 'NSW')": 1,
+ "('basic_amt', 'QLD')": 2,
+ }
+ ]