Skip to content

Commit

Permalink
fix(python): Add height check to frame-level row indexing when key is…
Browse files Browse the repository at this point in the history
… int (#20778)
  • Loading branch information
mcrumiller authored Jan 21, 2025
1 parent f826c32 commit 064e661
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions py-polars/polars/_utils/getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,10 @@ def _select_rows(
) -> DataFrame | Series:
"""Select one or more rows from the DataFrame."""
if isinstance(key, int):
num_rows = len(df)
if (key >= num_rows) or (key < -num_rows):
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
19 changes: 19 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,22 @@ 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]


@pytest.mark.parametrize("idx", [3, 99, -4, -99])
def test_select_oob_element_20775_too_large(idx: int) -> None:
df = pl.DataFrame({"a": [1, 2, 3]})
with pytest.raises(
IndexError,
match=f"index {idx} is out of bounds for sequence of length 3",
):
df[idx, "a"]

0 comments on commit 064e661

Please sign in to comment.