Skip to content

Commit 51c6a05

Browse files
kykosicjreback
authored andcommitted
BUG: Cleaner exception when .iloc called with non-integer list (#25759)
1 parent 48d76d6 commit 51c6a05

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ Interval
252252
Indexing
253253
^^^^^^^^
254254

255-
-
255+
- Improved exception message when calling :meth:`DataFrame.iloc` with a list of non-numeric objects (:issue:`25753`).
256256
-
257257
-
258258

pandas/core/indexing.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from pandas.core.dtypes.common import (
1414
ensure_platform_int, is_float, is_integer, is_integer_dtype, is_iterator,
15-
is_list_like, is_scalar, is_sequence, is_sparse)
15+
is_list_like, is_numeric_dtype, is_scalar, is_sequence, is_sparse)
1616
from pandas.core.dtypes.generic import ABCDataFrame, ABCPanel, ABCSeries
1717
from pandas.core.dtypes.missing import _infer_fill_value, isna
1818

@@ -2074,10 +2074,15 @@ def _validate_key(self, key, axis):
20742074
# so don't treat a tuple as a valid indexer
20752075
raise IndexingError('Too many indexers')
20762076
elif is_list_like_indexer(key):
2077-
# check that the key does not exceed the maximum size of the index
20782077
arr = np.array(key)
20792078
len_axis = len(self.obj._get_axis(axis))
20802079

2080+
# check that the key has a numeric dtype
2081+
if not is_numeric_dtype(arr.dtype):
2082+
raise IndexError(".iloc requires numeric indexers, got "
2083+
"{arr}".format(arr=arr))
2084+
2085+
# check that the key does not exceed the maximum size of the index
20812086
if len(arr) and (arr.max() >= len_axis or arr.min() < -len_axis):
20822087
raise IndexError("positional indexers are out-of-bounds")
20832088
else:

pandas/tests/indexing/test_iloc.py

+15
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,21 @@ def check(result, expected):
118118
with pytest.raises(IndexError, match=msg):
119119
dfl.iloc[:, 4]
120120

121+
@pytest.mark.parametrize("index,columns", [(np.arange(20), list('ABCDE'))])
122+
@pytest.mark.parametrize("index_vals,column_vals", [
123+
([slice(None), ['A', 'D']]),
124+
(['1', '2'], slice(None)),
125+
([pd.datetime(2019, 1, 1)], slice(None))])
126+
def test_iloc_non_integer_raises(self, index, columns,
127+
index_vals, column_vals):
128+
# GH 25753
129+
df = DataFrame(np.random.randn(len(index), len(columns)),
130+
index=index,
131+
columns=columns)
132+
msg = '.iloc requires numeric indexers, got'
133+
with pytest.raises(IndexError, match=msg):
134+
df.iloc[index_vals, column_vals]
135+
121136
def test_iloc_getitem_int(self):
122137

123138
# integer

0 commit comments

Comments
 (0)