我想计算rolling_sum,但不是在当前行上方的x行上,而是在当前行下方的x行上.

我的解决方案是在应用rolling_sum之前使用descending=True对数据帧进行排序,然后再对descending=False进行排序.

My solution:

import polars as pl

# Dummy dataset
df = pl.DataFrame({
        "Date": [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
        "Close": [-1, 1, 2, 3, 4, 4, 3, 2, 1, -1],
        "Company": ["A", "A", "A","A", "A",  "B", "B", "B", "B", "B"]
    })

# Solution using sort twice

(
    df
    .sort(by=["Company", "Date"], descending=[True, True])
    .with_columns(
        pl.col("Close").rolling_sum(3).over("Company").alias("Cumsum_lead")
    )
    .sort(by=["Company", "Date"], descending=[False, False])
)

Is there a better solution?

更好的意思是:

  • 更高效的计算和/或
  • 代码更少/更易于阅读

谢谢!

EDIT:

我刚刚想到了另一个解决方案,它完全避免了对列进行排序/反转:使用shift

(
    df
    .with_columns(
        pl.col("Close")
      .rolling_sum(3)
      .shift(-2)
      .over("Company").alias("Cumsum_lead"))
)

推荐答案

您可以避免对行进行排序,而是使用pl.Expr.reverse将特定列反转两次.

(
    df
    .with_columns(
        pl.col("Close")
        .reverse().rolling_sum(3).reverse()
        .over("Company").alias("Cumsum_lead")
    )
)

出于可读性的考虑,还可以将其包装到助手函数中.

def rolling_sum_lead(expr: pl.Expr, window_size: int) -> pl.Expr:
    return expr.reverse().rolling_sum(window_size).reverse()

(
    df
    .with_columns(
        rolling_sum_lead(pl.col("Close"), 3).over("Company").alias("Cumsum_lead")
    )
)

在我的机器上,这需要每环124uS±5.67uS,而使用pl.DataFrame.sort的解决方案每环需要205uS±6.9uS.

Python相关问答推荐

如何才能知道Python中2列表中的巧合.顺序很重要,但当1个失败时,其余的不应该失败或是0巧合

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

滚动和,句号来自Pandas列

沿着数组中的轴计算真实条目

根据二元组列表在pandas中创建新列

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

django禁止直接分配到多对多集合的前端.使用user.set()

如何在python polars中停止otherate(),当使用when()表达式时?

如何请求使用Python将文件下载到带有登录名的门户网站?

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

有没有一种方法可以从python的pussompy比较结果中提取文本?

如何在WSL2中更新Python到最新版本(3.12.2)?

使用Python查找、替换和调整PDF中的图像'

如何排除prefecture_related中查询集为空的实例?

如何使用Azure Function将xlsb转换为xlsx?

在第一次调用时使用不同行为的re. sub的最佳方式

有没有一种方法可以在朗肯代理中集成向量嵌入

如果服务器设置为不侦听创建,则QWebSocket客户端不连接到QWebSocketServer;如果服务器稍后开始侦听,则不连接

递归链表反转与打印语句挂起

在Pandas 中以十六进制显示/打印列?