Skip to content

Commit 588d19a

Browse files
committed
Add height check for single index
1 parent 6753bb6 commit 588d19a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

py-polars/polars/_utils/getitem.py

+3
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,9 @@ def _select_rows(
291291
) -> DataFrame | Series:
292292
"""Select one or more rows from the DataFrame."""
293293
if isinstance(key, int):
294+
if key >= len(df):
295+
msg = f"index {key} is out of bounds for DataFrame of height {len(df)}"
296+
raise IndexError(msg)
294297
return df.slice(key, 1)
295298

296299
if isinstance(key, slice):

py-polars/tests/unit/dataframe/test_df.py

+18
Original file line numberDiff line numberDiff line change
@@ -2995,3 +2995,21 @@ def test_get_column_after_drop_20119() -> None:
29952995
df.drop_in_place("a")
29962996
c = df.get_column("c")
29972997
assert_series_equal(c, pl.Series("c", ["C"]))
2998+
2999+
3000+
def test_select_oob_row_20775() -> None:
3001+
df = pl.DataFrame({"a": [1, 2, 3]})
3002+
with pytest.raises(
3003+
IndexError,
3004+
match="index 99 is out of bounds for DataFrame of height 3",
3005+
):
3006+
df[99]
3007+
3008+
3009+
def test_select_oob_element_20775() -> None:
3010+
df = pl.DataFrame({"a": [1, 2, 3]})
3011+
with pytest.raises(
3012+
IndexError,
3013+
match="index 99 is out of bounds for sequence of length 3",
3014+
):
3015+
df[99, "a"]

0 commit comments

Comments
 (0)