Skip to content

Commit 1fe373f

Browse files
authored
44414 data frame attributes not propagating with astype (#44680)
1 parent 0635a25 commit 1fe373f

File tree

4 files changed

+22
-1
lines changed

4 files changed

+22
-1
lines changed

doc/source/whatsnew/v1.4.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -652,7 +652,7 @@ Conversion
652652
- Bug in :class:`IntegerDtype` not allowing coercion from string dtype (:issue:`25472`)
653653
- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`)
654654
- Bug in :meth:`DataFrame.convert_dtypes` not returning the correct type when a subclass does not overload :meth:`_constructor_sliced` (:issue:`43201`)
655-
-
655+
- Bug in :meth:`DataFrame.astype` not propagating ``attrs`` from the original :class:`DataFrame` (:issue:`44414`)
656656

657657
Strings
658658
^^^^^^^

pandas/core/generic.py

+1
Original file line numberDiff line numberDiff line change
@@ -5888,6 +5888,7 @@ def astype(
58885888
# GH 19920: retain column metadata after concat
58895889
result = concat(results, axis=1, copy=False)
58905890
result.columns = self.columns
5891+
result = result.__finalize__(self, method="astype")
58915892
# https://github.com/python/mypy/issues/8354
58925893
return cast(NDFrameT, result)
58935894

pandas/tests/frame/methods/test_astype.py

+10
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,16 @@ def test_astype_noncontiguous(self, index_slice):
714714
expected = df.iloc[index_slice]
715715
tm.assert_frame_equal(result, expected, check_dtype=False)
716716

717+
def test_astype_retain_attrs(self, any_numpy_dtype):
718+
# GH#44414
719+
df = DataFrame({"a": [0, 1, 2], "b": [3, 4, 5]})
720+
df.attrs["Location"] = "Michigan"
721+
722+
result = df.astype({"a": any_numpy_dtype}).attrs
723+
expected = df.attrs
724+
725+
tm.assert_dict_equal(expected, result)
726+
717727

718728
class TestAstypeCategorical:
719729
def test_astype_from_categorical3(self):

pandas/tests/series/methods/test_astype.py

+10
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,16 @@ def test_astype_ea_to_datetimetzdtype(self, dtype):
396396

397397
tm.assert_series_equal(result, expected)
398398

399+
def test_astype_retain_Attrs(self, any_numpy_dtype):
400+
# GH#44414
401+
ser = Series([0, 1, 2, 3])
402+
ser.attrs["Location"] = "Michigan"
403+
404+
result = ser.astype(any_numpy_dtype).attrs
405+
expected = ser.attrs
406+
407+
tm.assert_dict_equal(expected, result)
408+
399409

400410
class TestAstypeString:
401411
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)