Skip to content

Backport PR #40592: REGR: where not copying on no-op #40634

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
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.2.4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Fixed regressions

- Fixed regression in :meth:`DataFrame.sum` when ``min_count`` greater than the :class:`DataFrame` shape was passed resulted in a ``ValueError`` (:issue:`39738`)
- Fixed regression in :meth:`DataFrame.to_json` raising ``AttributeError`` when run on PyPy (:issue:`39837`)
- Fixed regression in :meth:`DataFrame.where` not returning a copy in the case of an all True condition (:issue:`39595`)
-

.. ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1458,7 +1458,7 @@ def where(
raise ValueError("where must have a condition that is ndarray like")

if cond.ravel("K").all():
result = values
result = values.copy()
else:
# see if we can operate on the entire block, or need item-by-item
# or if we are a single block (ndim == 1)
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/frame/indexing/test_where.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,3 +653,20 @@ def test_where_categorical_filtering(self):
expected.loc[0, :] = np.nan

tm.assert_equal(result, expected)


def test_where_copies_with_noop(frame_or_series):
# GH-39595
result = frame_or_series([1, 2, 3, 4])
expected = result.copy()
col = result[0] if frame_or_series is DataFrame else result

where_res = result.where(col < 5)
where_res *= 2

tm.assert_equal(result, expected)

where_res = result.where(col > 5, [1, 2, 3, 4])
where_res *= 2

tm.assert_equal(result, expected)