diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2249790b7ff1b..fd87a85f378d0 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -652,7 +652,7 @@ Conversion - Bug in :class:`IntegerDtype` not allowing coercion from string dtype (:issue:`25472`) - 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`) Strings ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 476e611eb20d6..260ced29b5a29 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5888,6 +5888,7 @@ def astype( # GH 19920: retain column metadata after concat result = concat(results, axis=1, copy=False) result.columns = self.columns + result = result.__finalize__(self, method="astype") # https://github.com/python/mypy/issues/8354 return cast(NDFrameT, result) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index feee03bbb91a2..d326ca3493977 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -714,6 +714,16 @@ def test_astype_noncontiguous(self, index_slice): expected = df.iloc[index_slice] tm.assert_frame_equal(result, expected, check_dtype=False) + def test_astype_retain_attrs(self, any_numpy_dtype): + # GH#44414 + df = DataFrame({"a": [0, 1, 2], "b": [3, 4, 5]}) + df.attrs["Location"] = "Michigan" + + result = df.astype({"a": any_numpy_dtype}).attrs + expected = df.attrs + + tm.assert_dict_equal(expected, result) + class TestAstypeCategorical: def test_astype_from_categorical3(self): diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index a20667655590b..0d5201849ea56 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -396,6 +396,16 @@ def test_astype_ea_to_datetimetzdtype(self, dtype): tm.assert_series_equal(result, expected) + def test_astype_retain_Attrs(self, any_numpy_dtype): + # GH#44414 + ser = Series([0, 1, 2, 3]) + ser.attrs["Location"] = "Michigan" + + result = ser.astype(any_numpy_dtype).attrs + expected = ser.attrs + + tm.assert_dict_equal(expected, result) + class TestAstypeString: @pytest.mark.parametrize(