我想问问周围有没有人知道如何在极地进行滚动索引? 我个人try 过一些不适合我的解决方案(我将在下面展示它们):
What I'd like to do:Indexing the number of occurrences within the past X days by Name 示例:假设我想对过go 2天内发生的事件进行索引:
Name | Date | Counter |
---|---|---|
John | 1 Jan 23 | 1 |
John | 1 Jan 23 | 2 |
John | 1 Jan 23 | 3 |
John | 1 Jan 23 | 4 |
John | 2 Jan 23 | 5 |
John | 2 Jan 23 | 6 |
John | 2 Jan 23 | 7 |
John | 2 Jan 23 | 8 |
John | 3 Jan 23 | 5 |
John | 3 Jan 23 | 6 |
New Guy | 1 Jan 23 | 1 |
在这种情况下,计数器从过go X天开始重置为"1"(例如,对于23年1月3日,从23年1月2日开始为"1"),或者如果检测到新名称
What I've tried:
df.groupby_rolling(index_column='Date', period='2d', by='Name', check_sorted=False).agg((pl.col("Date").rank(method='ordinal')).alias("Counter"))
上面不起作用,因为它输出:
Name | Date | Counter |
---|---|---|
John | 1 Jan 23 | 1,2,3,4 |
John | 1 Jan 23 | 1,2,3,4 |
John | 1 Jan 23 | 1,2,3,4 |
John | 1 Jan 23 | 1,2,3,4 |
John | 2 Jan 23 | 1...8 |
John | 2 Jan 23 | 1...8 |
John | 2 Jan 23 | 1...8 |
John | 2 Jan 23 | 1...8 |
John | 3 Jan 23 | 1...6 |
John | 3 Jan 23 | 1...6 |
New Guy | 1 Jan 23 | 1 |
df.with_columns( Counter=pl.col("mask").rolling_sum(window_size='2d', by="Date") )
我创建了一个列"Mask",它只是一列"1",并试图将它们相加,但它输出:
Name | Date | Mask | Counter |
---|---|---|---|
John | 1 Jan 23 | 1 | 4 |
John | 1 Jan 23 | 1 | 4 |
John | 1 Jan 23 | 1 | 4 |
John | 1 Jan 23 | 1 | 4 |
John | 2 Jan 23 | 1 | 8 |
John | 2 Jan 23 | 1 | 8 |
John | 2 Jan 23 | 1 | 8 |
John | 2 Jan 23 | 1 | 8 |
John | 3 Jan 23 | 1 | 6 |
John | 3 Jan 23 | 1 | 6 |
而且它也无法正确处理"New Guy",因为rolling_sum无法通过="Name","Date"来处理
df.with_columns(Counter = pl.col("Date").rank(method='ordinal').over(["Name", "Date"]) )
上述代码工作正常,但只能用于同一天内的索引(即period="1d")
附加注释:我也在Excel中做到了这一点,并且还使用了使用"for"-循环的brug/raw方法.两者都工作得很完美,但它们在处理大量数据时遇到了困难.
What I read: 答案中的一些帮助参考:(大多数都不起作用,因为它们有固定的滚动窗口,而不是"Date"的动态窗口)
How to implement rolling rank in Polars version 0.19
https://github.com/pola-rs/polars/issues/4808
How to do group_by_rolling grouped by day by hour in polars in Python?
How to groupby and rolling in polars?
https://docs.pola.rs/py-polars/html/reference/series/api/polars.Series.rank.html
https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.groupby_rolling.html