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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: pandas series with columns the same as index name (#6418)
Myles Scolnick9456f4ad8f7f
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 6be1e75ac7..731aed0399 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -145,6 +145,28 @@ class PandasTableManagerFactory(TableManagerFactory):)index_levels = result.index.nlevels++ # Check for name conflicts between index names and column names+ # to avoid "cannot insert x, already exists" error+ conflicting_names = set(index_names) & set(result.columns)+ if conflicting_names:+ # Create new names, handling None values+ new_names: list[str] = []+ for name in result.index.names:+ if name in conflicting_names:+ new_names.append(f"{name}_index")+ else:+ new_names.append(str(name))++ # Rename the index to avoid conflict+ if isinstance(result.index, pd.MultiIndex):+ result.index = result.index.set_names(new_names)+ else:+ result.index = result.index.rename(new_names[0])++ # Update index_names to reflect the rename+ index_names = result.index.names+result = result.reset_index()if unnamed_indexes:diff --git a/tests/_output/formatters/test_pandas.py b/tests/_output/formatters/test_pandas.pyindex 0ff3701f3d..bd522f1eb2 100644--- a/tests/_output/formatters/test_pandas.py+++ b/tests/_output/formatters/test_pandas.py@@ -88,3 +88,27 @@ def test_pandas_formatters_with_truncate() -> None:mime, content = formatter(df.dtypes)assert mime == "text/html"assert content.startswith("<table")++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_pandas_series_name_conflict_opinionated() -> None:+ """Test that Series with same name as index works with opinionated formatter."""+ register_formatters()++ import pandas as pd++ # Create a Series with the same name as its index (GitHub issue #6385)+ series = pd.Series(+ data=[1, 2, 3], name="x", index=pd.Index([1, 2, 3], name="x")+ )++ # This should not raise "ValueError: cannot insert x, already exists"+ formatter = get_formatter(series, include_opinionated=True)+ assert formatter+ mime, content = formatter(series)+ # The key test is that it doesn't raise an exception+ # The mime type might be either application/json or text/html depending on the formatter+ assert mime in ("application/json", "text/html")+ # Should successfully format without errors+ assert content is not None+ assert len(content) > 0diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex 405705c3ad..c4ff64313f 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -1213,3 +1213,54 @@ class TestPandasTableManager(unittest.TestCase):assert json_data[0]["name"] == "test1"assert json_data[1]["name"] == "test2"assert json_data[2]["name"] == "test3"++ def test_to_json_series_name_conflict(self) -> None:+ import pandas as pd++ # Test case from GitHub issue #6385: Series with same name as index+ # This should not raise "ValueError: cannot insert x, already exists"+ series = pd.Series(+ data=[1, 2, 3], name="x", index=pd.Index([1, 2, 3], name="x")+ )++ # Convert to DataFrame (mimics what _show_marimo_series does)+ df = series.to_frame()+ manager = self.factory.create()(df)++ # This should not raise any errors+ json_data = json.loads(manager.to_json())++ # Verify the data structure - index should be renamed to avoid conflict+ assert len(json_data) == 3+ # The conflicting index name should be renamed with "_index" suffix+ assert "x_index" in json_data[0]+ assert "x" in json_data[0]+ # Check data values+ assert json_data[0]["x_index"] == 1+ assert json_data[0]["x"] == 1+ assert json_data[1]["x_index"] == 2+ assert json_data[1]["x"] == 2+ assert json_data[2]["x_index"] == 3+ assert json_data[2]["x"] == 3++ def test_to_json_multi_index_name_conflict(self) -> None:+ import pandas as pd++ # Test case with MultiIndex where one level conflicts with column+ df = pd.DataFrame(+ {"x": [1, 2, 3], "y": [4, 5, 6]},+ index=pd.MultiIndex.from_tuples(+ [(1, 4), (2, 5), (3, 6)], names=["x", "z"]+ ),+ )+ manager = self.factory.create()(df)++ # This should not raise any errors+ json_data = json.loads(manager.to_json())++ # Verify the data structure - conflicting index name should be renamed+ assert len(json_data) == 3+ assert "x_index" in json_data[0] # Renamed index level+ assert "z" in json_data[0] # Non-conflicting index level+ assert "x" in json_data[0] # Original column+ assert "y" in json_data[0] # Original column