Skip to content

Commit 0c30665

Browse files
committed
Merge pull request #5512 from jreback/indexing_bug
BUG: Fixed various setitem with iterable that does not have a matching length to the indexer (GH5508)
2 parents 705b677 + 9e70c10 commit 0c30665

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

doc/source/release.rst

+2
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,8 @@ Bug Fixes
805805
- ``pd.to_timedelta`` of a scalar returns a scalar (:issue:`5410`)
806806
- ``pd.to_timedelta`` accepts ``NaN`` and ``NaT``, returning ``NaT`` instead of raising (:issue:`5437`)
807807
- performance improvements in ``isnull`` on larger size pandas objects
808+
- Fixed various setitem with 1d ndarray that does not have a matching
809+
length to the indexer (:issue:`5508`)
808810

809811
pandas 0.12.0
810812
-------------

pandas/core/indexing.py

+4
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,10 @@ def can_do_equal_len():
365365
# per label values
366366
else:
367367

368+
if len(labels) != len(value):
369+
raise ValueError('Must have equal len keys and value when'
370+
' setting with an iterable')
371+
368372
for item, v in zip(labels, value):
369373
setter(item, v)
370374
else:

pandas/tests/test_indexing.py

+29
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,35 @@ def test_iloc_getitem_frame(self):
650650
# trying to use a label
651651
self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j','D']))
652652

653+
def test_setitem_ndarray_1d(self):
654+
# GH5508
655+
656+
# len of indexer vs length of the 1d ndarray
657+
df = DataFrame(index=Index(lrange(1,11)))
658+
df['foo'] = np.zeros(10, dtype=np.float64)
659+
df['bar'] = np.zeros(10, dtype=np.complex)
660+
661+
# invalid
662+
def f():
663+
df.ix[2:5, 'bar'] = np.array([2.33j, 1.23+0.1j, 2.2])
664+
self.assertRaises(ValueError, f)
665+
666+
# valid
667+
df.ix[2:5, 'bar'] = np.array([2.33j, 1.23+0.1j, 2.2, 1.0])
668+
669+
result = df.ix[2:5, 'bar']
670+
expected = Series([2.33j, 1.23+0.1j, 2.2, 1.0],index=[2,3,4,5])
671+
assert_series_equal(result,expected)
672+
673+
# dtype getting changed?
674+
df = DataFrame(index=Index(lrange(1,11)))
675+
df['foo'] = np.zeros(10, dtype=np.float64)
676+
df['bar'] = np.zeros(10, dtype=np.complex)
677+
678+
def f():
679+
df[2:5] = np.arange(1,4)*1j
680+
self.assertRaises(ValueError, f)
681+
653682
def test_iloc_setitem_series(self):
654683
""" originally from test_series.py """
655684
df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD'))

0 commit comments

Comments
 (0)