diff --git a/py-polars/polars/_utils/getitem.py b/py-polars/polars/_utils/getitem.py index 05404437c0ce..364da0ff91f8 100644 --- a/py-polars/polars/_utils/getitem.py +++ b/py-polars/polars/_utils/getitem.py @@ -291,6 +291,9 @@ def _select_rows( ) -> DataFrame | Series: """Select one or more rows from the DataFrame.""" if isinstance(key, int): + if key >= len(df): + msg = f"index {key} is out of bounds for DataFrame of height {len(df)}" + raise IndexError(msg) return df.slice(key, 1) if isinstance(key, slice): diff --git a/py-polars/tests/unit/dataframe/test_df.py b/py-polars/tests/unit/dataframe/test_df.py index 8c2fafcdd279..6fd66aa5bb3d 100644 --- a/py-polars/tests/unit/dataframe/test_df.py +++ b/py-polars/tests/unit/dataframe/test_df.py @@ -2995,3 +2995,21 @@ def test_get_column_after_drop_20119() -> None: df.drop_in_place("a") c = df.get_column("c") assert_series_equal(c, pl.Series("c", ["C"])) + + +def test_select_oob_row_20775() -> None: + df = pl.DataFrame({"a": [1, 2, 3]}) + with pytest.raises( + IndexError, + match="index 99 is out of bounds for DataFrame of height 3", + ): + df[99] + + +def test_select_oob_element_20775() -> None: + df = pl.DataFrame({"a": [1, 2, 3]}) + with pytest.raises( + IndexError, + match="index 99 is out of bounds for sequence of length 3", + ): + df[99, "a"]