Skip to content

Commit 5592171

Browse files
committed
BUGFIX: length_of_indexer() can return incorrect values that break slice assignments.
BUG DESCRIPTION: length_of_indexer() (defined in pandas/core/indexing.py) returns incorrect result if (stop-start) is not divisible by step. As a consequence some slice assignments throw exceptions. Affected panda versions: 0.16.x, 0.15.x, current git master. HOW TO REPRODUCE: import pandas as pd sr= pd.Series([-1]*6) # series with 6 elements indexed from 0 to 5. sr[0::2]= [0,2,4] # setting even elements works fine! sr[1::2]= [1,3,5] # setting odd elements results in error: .../pandas/core/internals.pyc in setitem(self, indexer, value) 568 if is_list_like(value) and l: 569 if len(value) != length_of_indexer(indexer, values): --> 570 raise ValueError("cannot set using a slice indexer with a " 571 "different length than the value") 572 ValueError: cannot set using a slice indexer with a different length than the value
1 parent e6c4f76 commit 5592171

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

pandas/core/indexing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1591,8 +1591,8 @@ def length_of_indexer(indexer, target=None):
15911591
if step is None:
15921592
step = 1
15931593
elif step < 0:
1594-
step = abs(step)
1595-
return (stop - start) / step
1594+
step = -step
1595+
return (stop - start + step-1) // step
15961596
elif isinstance(indexer, (ABCSeries, Index, np.ndarray, list)):
15971597
return len(indexer)
15981598
elif not is_list_like_indexer(indexer):

pandas/tests/test_indexing.py

+7
Original file line numberDiff line numberDiff line change
@@ -1438,6 +1438,13 @@ def test_iloc_setitem_series(self):
14381438
result = s.iloc[:4]
14391439
assert_series_equal(result, expected)
14401440

1441+
s= Series([-1]*6)
1442+
s.iloc[0::2]= [0,2,4]
1443+
s.iloc[1::2]= [1,3,5]
1444+
result = s
1445+
expected= Series([0,1,2,3,4,5])
1446+
assert_series_equal(result, expected)
1447+
14411448
def test_iloc_setitem_list_of_lists(self):
14421449

14431450
# GH 7551

0 commit comments

Comments
 (0)