Skip to content

Commit f87de21

Browse files
committed
BUG: Fix _validate_key to handle ExtensionArray correctly GH#61311
1 parent 73db25d commit f87de21

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

pandas/core/indexing.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1609,9 +1609,16 @@ def _validate_key(self, key, axis: AxisInt) -> None:
16091609
if not is_numeric_dtype(arr.dtype):
16101610
raise IndexError(f".iloc requires numeric indexers, got {arr}")
16111611

1612-
# check that the key does not exceed the maximum size of the index
1613-
if len(arr) and (arr.max() >= len_axis or arr.min() < -len_axis):
1614-
raise IndexError("positional indexers are out-of-bounds")
1612+
if len(arr):
1613+
# convert to numpy array for min/max with ExtensionArrays
1614+
if hasattr(arr, "to_numpy"):
1615+
np_arr = arr.to_numpy()
1616+
else:
1617+
np_arr = np.asarray(arr)
1618+
1619+
# check that the key does not exceed the maximum size
1620+
if np.max(np_arr) >= len_axis or np.min(np_arr) < -len_axis:
1621+
raise IndexError("positional indexers are out-of-bounds")
16151622
else:
16161623
raise ValueError(f"Can only index by location with a [{self._valid_types}]")
16171624

pandas/tests/indexing/test_iloc.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1478,3 +1478,14 @@ def test_iloc_nullable_int64_size_1_nan(self):
14781478
result = DataFrame({"a": ["test"], "b": [np.nan]})
14791479
with pytest.raises(TypeError, match="Invalid value"):
14801480
result.loc[:, "b"] = result.loc[:, "b"].astype("Int64")
1481+
1482+
def test_iloc_arrow_extension_array(self):
1483+
# GH#61311
1484+
pytest.importorskip("pyarrow")
1485+
1486+
df = DataFrame({"a": [1, 2], "c": [0, 2], "d": ["c", "a"]})
1487+
1488+
df_arrow = df.convert_dtypes(dtype_backend="pyarrow")
1489+
result = df_arrow.iloc[:, df_arrow["c"]]
1490+
expected = df_arrow.iloc[:, [0, 2]]
1491+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)