Skip to content

Commit 50795e3

Browse files
fix Error Indexing DafaFrame with a 0-d array
closes #21946
1 parent 716efd3 commit 50795e3

File tree

4 files changed

+13
-2
lines changed

4 files changed

+13
-2
lines changed

Diff for: doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,7 @@ Indexing
501501
- Fixed ``DataFrame[np.nan]`` when columns are non-unique (:issue:`21428`)
502502
- Bug when indexing :class:`DatetimeIndex` with nanosecond resolution dates and timezones (:issue:`11679`)
503503
- Bug where indexing with a Numpy array containing negative values would mutate the indexer (:issue:`21867`)
504+
- Bug where indexing with a 0-dimensional array would error with an unhelpful stack trace (:issue: `21946`)
504505

505506
Missing
506507
^^^^^^^

Diff for: pandas/core/indexes/base.py

+2
Original file line numberDiff line numberDiff line change
@@ -4178,6 +4178,8 @@ def _validate_indexer(self, form, key, kind):
41784178
pass
41794179
elif is_integer(key):
41804180
pass
4181+
elif key.ndim == 0:
4182+
self._invalid_indexer(form, key)
41814183
elif kind in ['iloc', 'getitem']:
41824184
self._invalid_indexer(form, key)
41834185
return key

Diff for: pandas/core/indexing.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -2692,8 +2692,9 @@ def is_nested_tuple(tup, labels):
26922692

26932693
def is_list_like_indexer(key):
26942694
# allow a list_like, but exclude NamedTuples which can be indexers
2695-
return is_list_like(key) and not (isinstance(key, tuple) and
2696-
type(key) is not tuple)
2695+
return (is_list_like(key)
2696+
and not (isinstance(key, tuple) and type(key) is not tuple)
2697+
and not np.array(key).ndim == 0)
26972698

26982699

26992700
def is_label_like(key):

Diff for: pandas/tests/indexing/test_indexing.py

+7
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,13 @@ def test_no_reference_cycle(self):
890890
del df
891891
assert wr() is None
892892

893+
def test_zero_index_iloc_raises(self):
894+
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
895+
ar = np.array(0)
896+
msg = 'Cannot index by location index with a non-integer key'
897+
tm.assert_raises_regex(TypeError, msg,
898+
lambda: df.iloc[ar])
899+
893900

894901
class TestSeriesNoneCoercion(object):
895902
EXPECTED_RESULTS = [

0 commit comments

Comments
 (0)