Skip to content

44414 data frame attributes not propagating with astype #44680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Dec 5, 2021
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^^
Expand Down
1 change: 1 addition & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/series/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down