Skip to content
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

REGR: ensure DataFrame.select_dtypes() returns a copy #48176

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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.4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.loc` not aligning index in some cases when setting a :class:`DataFrame` (:issue:`47578`)
- Fixed regression in :meth:`DataFrame.loc` setting a length-1 array like value to a single value in the DataFrame (:issue:`46268`)
- Fixed regression in setting ``None`` or non-string value into a ``string``-dtype Series using a mask (:issue:`47628`)
- Fixed regression in :meth:`DataFrame.select_dtypes` returning a view on the original DataFrame (:issue:`48090`)
- Fixed regression in :func:`merge` throwing an error when passing a :class:`Series` with a multi-level name (:issue:`47946`)
- Fixed regression in :meth:`DataFrame.eval` creating a copy when updating inplace (:issue:`47449`)
-
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4706,7 +4706,7 @@ def predicate(arr: ArrayLike) -> bool:

return True

mgr = self._mgr._get_data_subset(predicate)
mgr = self._mgr._get_data_subset(predicate, copy=True)
Copy link
Member

Choose a reason for hiding this comment

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

instead of adding a keyword in the Manager method could we just do a .copy after _get_data_subset?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, good point. I was originally thinking to add it here to ensure that the manager can be smarter to know what needs to be copied and what not. But since the predicate is based on the block dtype, this can never split any blocks, so I suppose there will never be such a case where the subset might already be a copy. So yes, doing a .copy() here is indeed much simpler.

There is one difference though: combine (used by _get_data_subset) doesn't do consolidation, while copy() does. So if your original dataframe is not fully consolidated, the current PR keeps more of the performance improvement of #42611. Of course, at the cost of an unconsolidated return value and a potential later consolidation.

Either way is fine for me. Doing a simpler copy() will also keep it closer to the previous behaviour since iloc also consolidates I think.

Copy link
Member

Choose a reason for hiding this comment

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

let's do the copy outside of internals

return type(self)(mgr).__finalize__(self)

def insert(
Expand Down
12 changes: 9 additions & 3 deletions pandas/core/internals/array_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,9 +477,12 @@ def is_view(self) -> bool:
def is_single_block(self) -> bool:
return len(self.arrays) == 1

def _get_data_subset(self: T, predicate: Callable) -> T:
def _get_data_subset(self: T, predicate: Callable, copy: bool = False) -> T:
indices = [i for i, arr in enumerate(self.arrays) if predicate(arr)]
arrays = [self.arrays[i] for i in indices]
if copy:
arrays = [self.arrays[i].copy() for i in indices]
else:
arrays = [self.arrays[i] for i in indices]
# TODO copy?
# Note: using Index.take ensures we can retain e.g. DatetimeIndex.freq,
# see test_describe_datetime_columns
Expand Down Expand Up @@ -1329,8 +1332,11 @@ def idelete(self, indexer) -> SingleArrayManager:
self._axes = [self._axes[0][to_keep]]
return self

def _get_data_subset(self, predicate: Callable) -> SingleArrayManager:
def _get_data_subset(
self, predicate: Callable, copy: bool = False
) -> SingleArrayManager:
# used in get_numeric_data / get_bool_data
# copy keyword is being ignored, only added for signature compat with base class
if predicate(self.array):
return type(self)(self.arrays, self._axes, verify_integrity=False)
else:
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/internals/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,9 +464,9 @@ def is_view(self) -> bool:

return False

def _get_data_subset(self: T, predicate: Callable) -> T:
def _get_data_subset(self: T, predicate: Callable, copy: bool = False) -> T:
blocks = [blk for blk in self.blocks if predicate(blk.values)]
return self._combine(blocks, copy=False)
return self._combine(blocks, copy=copy)

def get_bool_data(self: T, copy: bool = False) -> T:
"""
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/methods/test_select_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,3 +456,12 @@ def test_np_bool_ea_boolean_include_number(self):
result = df.select_dtypes(include="number")
expected = DataFrame({"a": [1, 2, 3]})
tm.assert_frame_equal(result, expected)

def test_select_dtypes_no_view(self):
# https://github.com/pandas-dev/pandas/issues/48090
# result of this method is not a view on the original dataframe
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df_orig = df.copy()
result = df.select_dtypes(include=["number"])
result.iloc[0, 0] = 0
tm.assert_frame_equal(df, df_orig)