Skip to content

Commit 104ef4d

Browse files
authored
BUG: convert_dtypes lose columns.names GH#41435 (#44997)
1 parent dd018ac commit 104ef4d

File tree

4 files changed

+12
-2
lines changed

4 files changed

+12
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,7 @@ Conversion
668668
- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`)
669669
- Bug in :meth:`DataFrame.convert_dtypes` not returning the correct type when a subclass does not overload :meth:`_constructor_sliced` (:issue:`43201`)
670670
- Bug in :meth:`DataFrame.astype` not propagating ``attrs`` from the original :class:`DataFrame` (:issue:`44414`)
671+
- Bug in :meth:`DataFrame.convert_dtypes` result losing ``columns.names`` (:issue:`41435`)
671672

672673
Strings
673674
^^^^^^^

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ def __init__(
368368
categories=None,
369369
ordered=None,
370370
dtype: Dtype | None = None,
371-
fastpath=False,
371+
fastpath: bool = False,
372372
copy: bool = True,
373373
):
374374

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6254,7 +6254,7 @@ def convert_dtypes(
62546254
for col_name, col in self.items()
62556255
]
62566256
if len(results) > 0:
6257-
result = concat(results, axis=1, copy=False)
6257+
result = concat(results, axis=1, copy=False, keys=self.columns)
62586258
cons = cast(Type["DataFrame"], self._constructor)
62596259
result = cons(result)
62606260
result = result.__finalize__(self, method="convert_dtypes")

pandas/tests/frame/methods/test_convert_dtypes.py

+9
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,12 @@ def test_convert_empty(self):
3232
# Empty DataFrame can pass convert_dtypes, see GH#40393
3333
empty_df = pd.DataFrame()
3434
tm.assert_frame_equal(empty_df, empty_df.convert_dtypes())
35+
36+
def test_convert_dtypes_retain_column_names(self):
37+
# GH#41435
38+
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
39+
df.columns.name = "cols"
40+
41+
result = df.convert_dtypes()
42+
tm.assert_index_equal(result.columns, df.columns)
43+
assert result.columns.name == "cols"

0 commit comments

Comments
 (0)