Skip to content

Commit dcd9e6c

Browse files
ydovzhenkojreback
authored andcommitted
BUG: np array indexer modifed in iloc (#21867)
1 parent fac8196 commit dcd9e6c

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v0.24.0.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -433,8 +433,7 @@ Indexing
433433
- ``DataFrame.__getitem__`` now accepts dictionaries and dictionary keys as list-likes of labels, consistently with ``Series.__getitem__`` (:issue:`21294`)
434434
- Fixed ``DataFrame[np.nan]`` when columns are non-unique (:issue:`21428`)
435435
- Bug when indexing :class:`DatetimeIndex` with nanosecond resolution dates and timezones (:issue:`11679`)
436-
437-
-
436+
- Bug where indexing with a Numpy array containing negative values would mutate the indexer (:issue:`21867`)
438437

439438
Missing
440439
^^^^^^^

pandas/core/indexing.py

+1
Original file line numberDiff line numberDiff line change
@@ -2596,6 +2596,7 @@ def maybe_convert_indices(indices, n):
25962596

25972597
mask = indices < 0
25982598
if mask.any():
2599+
indices = indices.copy()
25992600
indices[mask] += n
26002601

26012602
mask = (indices >= n) | (indices < 0)

pandas/tests/indexing/test_iloc.py

+15
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,21 @@ def test_iloc_getitem_neg_int(self):
126126
typs=['labels', 'mixed', 'ts', 'floats', 'empty'],
127127
fails=IndexError)
128128

129+
def test_iloc_array_not_mutating_negative_indices(self):
130+
131+
# GH 21867
132+
array_with_neg_numbers = np.array([1, 2, -1])
133+
array_copy = array_with_neg_numbers.copy()
134+
df = pd.DataFrame({
135+
'A': [100, 101, 102],
136+
'B': [103, 104, 105],
137+
'C': [106, 107, 108]},
138+
index=[1, 2, 3])
139+
df.iloc[array_with_neg_numbers]
140+
tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
141+
df.iloc[:, array_with_neg_numbers]
142+
tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
143+
129144
def test_iloc_getitem_list_int(self):
130145

131146
# list of ints

0 commit comments

Comments
 (0)