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 convert non-string columns to string columns (#6000)
Myles Scolnickc099b46035b7
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex 6e1fb3a3e4..cc4d9493fd 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -350,5 +350,5 @@ def _sanitize_dtypes(nw.col(column_name).cast(nw.UInt64))except Exception as e:- LOGGER.warning(f"Failed to sanitize dtypes: {str(e)}")+ LOGGER.warning(f"Failed to sanitize dtypes: {e}")return column_datadiff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.pyindex ebab61d3f1..b981917c57 100644--- a/marimo/_output/data/data.py+++ b/marimo/_output/data/data.py@@ -199,9 +199,17 @@ def sanitize_json_bigint(MAX_SAFE_INTEGER = 9007199254740991MIN_SAFE_INTEGER = -9007199254740991+ def convert_key(key: Any) -> Any:+ # Keys must be str, int, float, bool, or None+ if key is None:+ return key+ if isinstance(key, (str, int, float, bool)):+ return key+ return str(key)+def convert_bigint(obj: Any) -> Any:if isinstance(obj, dict):- return {k: convert_bigint(v) for k, v in obj.items()} # type: ignore+ return {convert_key(k): convert_bigint(v) for k, v in obj.items()} # type: ignoreelif isinstance(obj, list):return [convert_bigint(item) for item in obj] # type: ignoreelif isinstance(obj, int) and (diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 6e048076d4..6be1e75ac7 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -62,7 +62,9 @@ class PandasTableManagerFactory(TableManagerFactory):def __init__(self, data: pd.DataFrame) -> None:data = _maybe_convert_geopandas_to_pandas(data)- self._original_data = self._handle_multi_col_indexes(data)+ data = self._handle_multi_col_indexes(data)+ data = self._handle_non_string_column_names(data)+ self._original_data = datasuper().__init__(nw.from_native(self._original_data))@cached_property@@ -195,8 +197,9 @@ class PandasTableManagerFactory(TableManagerFactory):)return PandasTableManager(_data)+ @classmethoddef _handle_multi_col_indexes(- self, data: pd.DataFrame+ cls, 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@@ -229,6 +232,21 @@ class PandasTableManagerFactory(TableManagerFactory):return data+ @classmethod+ def _handle_non_string_column_names(+ cls, data: pd.DataFrame+ ) -> pd.DataFrame:+ if not isinstance(data.columns, pd.Index):+ return data++ if len(data.columns) > 0 and not isinstance(+ data.columns[0], str+ ):+ data.columns = pd.Index(+ [str(name) for name in data.columns]+ )+ return data+# We override the default implementation to use pandas# headersdef get_row_headers(self) -> FieldTypes:diff --git a/tests/_output/test_data.py b/tests/_output/test_data.pyindex 51aa340205..c9e9a24350 100644--- a/tests/_output/test_data.py+++ b/tests/_output/test_data.py@@ -71,3 +71,14 @@ def test_sanitize_json_bigint() -> None:mo_data.sanitize_json_bigint(data_dict)== '{"bigint":"9007199254740992","nested":{"bigint":"9007199254740993","regular":42}}' # noqa: E501)+++def test_sanitize_json_bigint_keys() -> None:+ import datetime++ data_dict = {+ datetime.date(2021, 1, 1): "date key",+ }+ assert (+ mo_data.sanitize_json_bigint(data_dict) == '{"2021-01-01":"date key"}'+ )diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.pyindex 3cb3fcd403..2c92a45a4a 100644--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py@@ -105,18 +105,18 @@ class TestDataframes:assert subject.value is dfassert subject._component_args["columns"] == [- [1, "integer", "int64"],- [2, "string", "object"],+ ["1", "integer", "int64"],+ ["2", "string", "object"],]assert subject._get_column_values(- GetColumnValuesArgs(column=1)+ GetColumnValuesArgs(column="1")) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)with pytest.raises(ColumnNotFound):subject._get_column_values(GetColumnValuesArgs(column="idk"))with pytest.raises(ColumnNotFound):- subject._get_column_values(GetColumnValuesArgs(column="1"))+ subject._get_column_values(GetColumnValuesArgs(column=1))@staticmethod@pytest.mark.skipif(@@ -238,10 +238,10 @@ class TestDataframes:# Test that we can get column values for non-string column namesassert subject._get_column_values(- GetColumnValuesArgs(column=0)+ GetColumnValuesArgs(column="0")) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)assert subject._get_column_values(- GetColumnValuesArgs(column=1.5)+ GetColumnValuesArgs(column="1.5")) == GetColumnValuesResponse(values=["a", "b", "c"], too_many_values=False)diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex e21bd59e5b..b439e5f0b3 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -1386,6 +1386,32 @@ def test_get_sample_values_with_metadata_only_frame(df: Any) -> None:assert sample_values == [][email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_get_column_names_with_timestamp_columns() -> None:+ """Test that get_column_names converts timestamp column names to strings."""+ import pandas as pd++ # Create a DataFrame with timestamp column names+ df = pd.DataFrame(+ {+ pd.Timestamp("2021-01-01"): [1, 2, 3],+ pd.Timestamp("2021-01-02"): [4, 5, 6],+ "regular_column": [7, 8, 9],+ }+ )++ manager = get_table_manager(df)+ column_names = manager.get_column_names()++ # All column names should be strings+ assert all(isinstance(name, str) for name in column_names), column_names+ assert set(column_names) == {+ "2021-01-01 00:00:00",+ "2021-01-02 00:00:00",+ "regular_column",+ }++@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")def test_get_sample_values_returns_primitives() -> None:"""Test that get_sample_values always returns primitive types."""diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 658edb8257..4cfe434185 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -2126,3 +2126,21 @@ def test_table_uses_default_max_columns():# Should use the default max_columns (50)assert table._max_columns == DEFAULT_MAX_COLUMNS+++ not DependencyManager.pandas.has(),+ reason="Pandas not installed",+)+def test_table_with_timestamp_column_name():+ # Create data with timestamps as columns+ import pandas as pd++ now = pd.Timestamp.now()+ data = {now + pd.Timedelta(minutes=i): [i, i + 1, i + 2] for i in range(5)}++ # Create table without specifying max_columns+ table = ui.table(pd.DataFrame(data))++ # Should use the default max_columns (50)+ assert table._max_columns == DEFAULT_MAX_COLUMNS