diff --git a/python/cudf/cudf/core/column/column.py b/python/cudf/cudf/core/column/column.py index 2535ba5ab8d..393afe4a5b9 100644 --- a/python/cudf/cudf/core/column/column.py +++ b/python/cudf/cudf/core/column/column.py @@ -1602,8 +1602,8 @@ def build_struct_column( Parameters ---------- - names : list-like - Field names to map to children dtypes + names : sequence of strings + Field names to map to children dtypes, must be strings. children : tuple mask: Buffer diff --git a/python/cudf/cudf/core/dataframe.py b/python/cudf/cudf/core/dataframe.py index 371404ca477..90119ba7b17 100644 --- a/python/cudf/cudf/core/dataframe.py +++ b/python/cudf/cudf/core/dataframe.py @@ -5864,8 +5864,16 @@ def to_struct(self, name=None): ----- Note that a copy of the columns is made. """ + if not all(isinstance(name, str) for name in self._data.names): + warnings.warn( + "DataFrame contains non-string column name(s). Struct column " + "requires field name to be string. Non-string column names " + "will be casted to string as the field name." + ) + field_names = [str(name) for name in self._data.names] + col = cudf.core.column.build_struct_column( - names=self._data.names, children=self._data.columns, size=len(self) + names=field_names, children=self._data.columns, size=len(self) ) return cudf.Series._from_data( cudf.core.column_accessor.ColumnAccessor( diff --git a/python/cudf/cudf/tests/test_struct.py b/python/cudf/cudf/tests/test_struct.py index dbff626c363..167f171fa26 100644 --- a/python/cudf/cudf/tests/test_struct.py +++ b/python/cudf/cudf/tests/test_struct.py @@ -205,6 +205,14 @@ def test_dataframe_to_struct(): df["a"][0] = 5 assert_eq(got, expect) + # check that a non-string (but convertible to string) named column can be + # converted to struct + df = cudf.DataFrame([[1, 2], [3, 4]], columns=[(1, "b"), 0]) + expect = cudf.Series([{"(1, 'b')": 1, "0": 2}, {"(1, 'b')": 3, "0": 4}]) + with pytest.warns(UserWarning, match="will be casted"): + got = df.to_struct() + assert_eq(got, expect) + @pytest.mark.parametrize( "series, slce",