Skip to content

Commit

Permalink
Add height check for single index
Browse files Browse the repository at this point in the history
  • Loading branch information
mcrumiller committed Jan 17, 2025
1 parent 6753bb6 commit e830977
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions py-polars/polars/_utils/getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
18 changes: 18 additions & 0 deletions py-polars/tests/unit/dataframe/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

0 comments on commit e830977

Please sign in to comment.