Skip to content

Commit

Permalink
BUG: Fix 57735 (#59335)
Browse files Browse the repository at this point in the history
* Revert "CLN: Remove special cases in indexing ops (#52063)"

This reverts commit 8e456d3.

* remove old comments, add test

* use better test name

* Update pandas/tests/indexing/test_loc.py

Co-authored-by: Matthew Roeschke <[email protected]>

* check for empty index first

* assert assign to empty does not change frame

* format

---------

Co-authored-by: Matthew Roeschke <[email protected]>
  • Loading branch information
matiaslindgren and mroeschke authored Jul 29, 2024
1 parent f25a09e commit aa4dc71
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
16 changes: 11 additions & 5 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,8 +810,11 @@ def _maybe_mask_setitem_value(self, indexer, value):

if is_scalar_indexer(icols, self.ndim - 1) and ndim == 1:
# e.g. test_loc_setitem_boolean_mask_allfalse
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
indexer = (newkey, icols)

elif (
Expand All @@ -827,8 +830,11 @@ def _maybe_mask_setitem_value(self, indexer, value):
indexer = (newkey, icols)

elif ndim == 2 and value.shape[1] == 1:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_frame(indexer, value)
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_frame(indexer, value)
indexer = (newkey, icols)
elif com.is_bool_indexer(indexer):
indexer = indexer.nonzero()[0]
Expand Down Expand Up @@ -2389,7 +2395,7 @@ def ravel(i):
new_ix = Index([new_ix])
else:
new_ix = Index(new_ix)
if ser.index.equals(new_ix):
if not len(new_ix) or ser.index.equals(new_ix):
if using_cow:
return ser
return ser._values.copy()
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3272,3 +3272,10 @@ def test_loc_index_alignment_for_series(self):
df.loc[:, "a"] = other
expected = DataFrame({"a": [999, 200], "b": [3, 4]})
tm.assert_frame_equal(expected, df)

def test_loc_reindexing_of_empty_index(self):
# GH 57735
df = DataFrame(index=[1, 1, 2, 2], data=["1", "1", "2", "2"])
df.loc[Series([False] * 4, index=df.index, name=0), 0] = df[0]
expected = DataFrame(index=[1, 1, 2, 2], data=["1", "1", "2", "2"])
tm.assert_frame_equal(df, expected)

0 comments on commit aa4dc71

Please sign in to comment.