From d9fb9ba6a268c782126a469a1deb7159c79901e8 Mon Sep 17 00:00:00 2001 From: Brock Date: Mon, 20 Dec 2021 19:32:53 -0800 Subject: [PATCH 1/2] BUG: convert_dtypes lose columns.names GH#41435 --- pandas/core/arrays/categorical.py | 2 +- pandas/core/generic.py | 2 +- pandas/tests/frame/methods/test_convert_dtypes.py | 9 +++++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index f9d066f1e694d..f8fecb6505ede 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -367,7 +367,7 @@ def __init__( categories=None, ordered=None, dtype: Dtype | None = None, - fastpath=False, + fastpath: bool = False, copy: bool = True, ): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e66086faf53af..a683599e20b77 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6254,7 +6254,7 @@ def convert_dtypes( for col_name, col in self.items() ] if len(results) > 0: - result = concat(results, axis=1, copy=False) + result = concat(results, axis=1, copy=False, keys=self.columns) cons = cast(Type["DataFrame"], self._constructor) result = cons(result) result = result.__finalize__(self, method="convert_dtypes") diff --git a/pandas/tests/frame/methods/test_convert_dtypes.py b/pandas/tests/frame/methods/test_convert_dtypes.py index a2d539d784d3c..ec639ed7132a4 100644 --- a/pandas/tests/frame/methods/test_convert_dtypes.py +++ b/pandas/tests/frame/methods/test_convert_dtypes.py @@ -32,3 +32,12 @@ def test_convert_empty(self): # Empty DataFrame can pass convert_dtypes, see GH#40393 empty_df = pd.DataFrame() tm.assert_frame_equal(empty_df, empty_df.convert_dtypes()) + + def test_convert_dtypes_retain_column_names(self): + # GH#41435 + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + df.columns.name = "cols" + + result = df.convert_dtypes() + tm.assert_index_equal(result.columns, df.columns) + assert result.columns.name == "cols" From 45ab9567f62f72ef86fd5986acacbbdbeb5d8702 Mon Sep 17 00:00:00 2001 From: Brock Date: Tue, 21 Dec 2021 08:30:19 -0800 Subject: [PATCH 2/2] whatsnew --- doc/source/whatsnew/v1.4.0.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2592be9c4a350..9f391f36e2d7d 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -667,6 +667,7 @@ Conversion - Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`) - Bug in :meth:`DataFrame.convert_dtypes` not returning the correct type when a subclass does not overload :meth:`_constructor_sliced` (:issue:`43201`) - Bug in :meth:`DataFrame.astype` not propagating ``attrs`` from the original :class:`DataFrame` (:issue:`44414`) +- Bug in :meth:`DataFrame.convert_dtypes` result losing ``columns.names`` (:issue:`41435`) Strings ^^^^^^^