'Take elements from each group in Polars

How can I take elements by index within each group of a Polars DataFrame? For example, if I wanted to get the first and third element of each group, I might try something like this:

import polars as pl

df = pl.DataFrame(dict(x=[1,0,1,0,1,0], y=[1,2,3,4,5,6]))

df.groupby('x').take([0,2])
# AttributeError: 'GroupBy' object has no attribute 'take'

But that does not work, obviously.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source