Skip to content

Commit

Permalink
add some index/range checks
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-beedie committed Sep 30, 2024
1 parent b72bd07 commit 885247b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4575,8 +4575,14 @@ def insert_column(self, index: int, column: IntoExprColumn) -> DataFrame:
│ 4 ┆ 13.0 ┆ true ┆ 0.0 │
└─────┴──────┴───────┴──────┘
"""
if index < 0:
if (original_index := index) < 0:
index = len(self.columns) + index
if index < 0:
msg = f"column index {original_index} is out of range (frame has {len(self.columns)} columns)"
raise IndexError(msg)
elif index > len(self.columns):
msg = f"column index {original_index} is out of range (frame has {len(self.columns)} columns)"
raise IndexError(msg)

if isinstance(column, pl.Series):
self._df.insert_column(index, column._s)
Expand Down
11 changes: 11 additions & 0 deletions py-polars/tests/unit/dataframe/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,17 @@ def test_insert_column() -> None:
)
assert_frame_equal(df, expected)

# check that we raise suitable index errors
for idx, column in (
(10, pl.col("v1").sqrt().alias("v1_sqrt")),
(-10, pl.Series("foo", [1, 2, 3])),
):
with pytest.raises(
IndexError,
match=rf"column index {idx} is out of range \(frame has 5 columns\)",
):
df.insert_column(idx, column)


def test_replace_column() -> None:
df = (
Expand Down

0 comments on commit 885247b

Please sign in to comment.