Skip to content

DataFrame.convert_dtypes doesn't preserve subclasses #44249

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 16 commits into from
Nov 13, 2021
Merged
Show file tree
Hide file tree
Changes from 12 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.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,7 @@ Conversion
- Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`)
- 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`)
-

Strings
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Literal,
Mapping,
Sequence,
Type,
cast,
final,
overload,
Expand Down Expand Up @@ -6219,8 +6220,12 @@ def convert_dtypes(
for col_name, col in self.items()
]
if len(results) > 0:
result = concat(results, axis=1, copy=False)
cons = cast(Type[DataFrame], self._constructor)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not super happy with this. Was getting the error

pandas/core/generic.py:6222: error: Argument 1 to "NDFrame" has incompatible type "DataFrame"; expected "Union[ArrayManager, SingleArrayManager, BlockManager, SingleBlockManager]"  [arg-type]

at https://github.com/pandas-dev/pandas/runs/4114882794?check_suite_focus=true, which refers to the line
result = self._constructor(concat(results, axis=1, copy=False)).

Bit confused because NDFrame._constructor raises an abstractmethod error, I'm guessing mypy is then reading the parent class PandasObject which returns type(self) i.e. in this case NDFrame. Then we're calling NDFrame with a DataFrame (the result of concat with more that 1 column). Finally the mypy type error seems to come from DataFrame in the __init__ of NDFrame which specifies the first argument is a Manager and not a DataFrame.

I guess given the return signature of concat is Series | DataFrame this is technically correct, but it seems awkward to use the DataFrame directly in the definition of the more general NDFrame

result = cons(result)
result = result.__finalize__(self, method="convert_dtypes")
# https://github.com/python/mypy/issues/8354
return cast(NDFrameT, concat(results, axis=1, copy=False))
return cast(NDFrameT, result)
else:
return self.copy()

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/frame/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@
import pandas._testing as tm


@pytest.fixture()
def gpd_style_subclass_df():
class SubclassedDataFrame(DataFrame):
@property
def _constructor(self):
return SubclassedDataFrame

return SubclassedDataFrame({"a": [1, 2, 3]})


class TestDataFrameSubclassing:
def test_frame_subclassing_and_slicing(self):
# Subclass frame and ensure it returns the right class on slicing it
Expand Down Expand Up @@ -704,6 +714,16 @@ def test_idxmax_preserves_subclass(self):
result = df.idxmax()
assert isinstance(result, tm.SubclassedSeries)

def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
# GH 43668
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
result = df.convert_dtypes()
assert isinstance(result, tm.SubclassedDataFrame)

result = gpd_style_subclass_df.convert_dtypes()
print(type(result), type(gpd_style_subclass_df))
assert isinstance(result, type(gpd_style_subclass_df))

def test_equals_subclass(self):
# https://github.com/pandas-dev/pandas/pull/34402
# allow subclass in both directions
Expand Down
5 changes: 1 addition & 4 deletions pandas/tests/generic/test_finalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,7 @@
operator.methodcaller("infer_objects"),
),
(pd.Series, ([1, 2],), operator.methodcaller("convert_dtypes")),
pytest.param(
(pd.DataFrame, frame_data, operator.methodcaller("convert_dtypes")),
marks=not_implemented_mark,
),
(pd.DataFrame, frame_data, operator.methodcaller("convert_dtypes")),
(pd.Series, ([1, None, 3],), operator.methodcaller("interpolate")),
(pd.DataFrame, ({"A": [1, None, 3]},), operator.methodcaller("interpolate")),
(pd.Series, ([1, 2],), operator.methodcaller("clip", lower=1)),
Expand Down