Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(python): Add height check to frame-level row indexing when key is int #20778

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"]
Loading