Skip to content

BUG: DataFrame.astype preserve subclasses GH#40810 #45272

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 4 commits into from
Jan 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ Numeric

Conversion
^^^^^^^^^^
- Bug in :meth:`DataFrame.astype` not preserving subclasses (:issue:`40810`)
- 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`)
-

Expand Down
6 changes: 6 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5891,6 +5891,12 @@ def astype(

# GH 19920: retain column metadata after concat
result = concat(results, axis=1, copy=False)
# GH#40810 retain subclass
# Incompatible types in assignment (expression has type "NDFrameT",
# variable has type "DataFrame")
# Argument 1 to "NDFrame" has incompatible type "DataFrame"; expected
# "Union[ArrayManager, SingleArrayManager, BlockManager, SingleBlockManager]"
result = self._constructor(result) # type: ignore[arg-type,assignment]
result.columns = self.columns
result = result.__finalize__(self, method="astype")
# https://github.com/python/mypy/issues/8354
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,13 @@ def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
result = gpd_style_subclass_df.convert_dtypes()
assert isinstance(result, type(gpd_style_subclass_df))

def test_astype_preserves_subclass(self):
# GH#40810
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})

result = df.astype({"A": np.int64, "B": np.int32, "C": np.float64})
assert isinstance(result, tm.SubclassedDataFrame)

def test_equals_subclass(self):
# https://github.com/pandas-dev/pandas/pull/34402
# allow subclass in both directions
Expand Down