Skip to content

Commit

Permalink
python improve dataframe slicing: closes #1082
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Aug 5, 2021
1 parent f733ea9 commit 253ca62
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
14 changes: 13 additions & 1 deletion py-polars/polars/eager/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,10 @@ def __getitem__(self, item: Any) -> Any:

# df[:]
if isinstance(item, slice):
# special case df[::-1]
if item.start is None and item.stop is None and item.step == -1:
return self.select(pl.col("*").reverse())

if getattr(item, "end", False):
raise ValueError("A slice with steps larger than 1 is not supported.")
if item.start is None:
Expand All @@ -942,8 +946,16 @@ def __getitem__(self, item: Any) -> Any:
stop = self.height
else:
stop = item.stop

length = stop - start
return self.slice(start, length)
if item.step is None:
# df[start:stop]
return self.slice(start, length)
else:
# df[start:stop:step]
return self.select(
pl.col("*").slice(start, length).take_every(item.step)
)

# select multiple columns
# df["foo", "bar"]
Expand Down
7 changes: 7 additions & 0 deletions py-polars/tests/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,13 @@ def test_selection():
assert df[2, "c"] == "c"
assert df[0, "a"] == 1

# more slicing
expect = pl.DataFrame({"a": [3, 2, 1], "b": [3.0, 2.0, 1.0], "c": ["c", "b", "a"]})
assert df[::-1].frame_equal(expect)

expect = pl.DataFrame({"a": [1, 3], "b": [1.0, 3.0], "c": ["a", "c"]})
assert df[::2].frame_equal(expect)


def test_from_arrow():
tbl = pa.table(
Expand Down

0 comments on commit 253ca62

Please sign in to comment.