Skip to content

Commit 37c43da

Browse files
authored
BUG: DataFrame.astype preserve subclasses GH#40810 (#45272)
1 parent db5c087 commit 37c43da

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ Numeric
184184

185185
Conversion
186186
^^^^^^^^^^
187+
- Bug in :meth:`DataFrame.astype` not preserving subclasses (:issue:`40810`)
187188
- Bug in constructing a :class:`Series` from a float-containing list or a floating-dtype ndarray-like (e.g. ``dask.Array``) and an integer dtype raising instead of casting like we would with an ``np.ndarray`` (:issue:`40110`)
188189
-
189190

pandas/core/generic.py

+6
Original file line numberDiff line numberDiff line change
@@ -5896,6 +5896,12 @@ def astype(
58965896

58975897
# GH 19920: retain column metadata after concat
58985898
result = concat(results, axis=1, copy=False)
5899+
# GH#40810 retain subclass
5900+
# Incompatible types in assignment (expression has type "NDFrameT",
5901+
# variable has type "DataFrame")
5902+
# Argument 1 to "NDFrame" has incompatible type "DataFrame"; expected
5903+
# "Union[ArrayManager, SingleArrayManager, BlockManager, SingleBlockManager]"
5904+
result = self._constructor(result) # type: ignore[arg-type,assignment]
58995905
result.columns = self.columns
59005906
result = result.__finalize__(self, method="astype")
59015907
# https://github.com/python/mypy/issues/8354

pandas/tests/frame/test_subclass.py

+7
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,13 @@ def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
723723
result = gpd_style_subclass_df.convert_dtypes()
724724
assert isinstance(result, type(gpd_style_subclass_df))
725725

726+
def test_astype_preserves_subclass(self):
727+
# GH#40810
728+
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
729+
730+
result = df.astype({"A": np.int64, "B": np.int32, "C": np.float64})
731+
assert isinstance(result, tm.SubclassedDataFrame)
732+
726733
def test_equals_subclass(self):
727734
# https://github.com/pandas-dev/pandas/pull/34402
728735
# allow subclass in both directions

0 commit comments

Comments
 (0)