让我们来个两极DF:

df = pl.DataFrame(
    {
    'date': ['2022-01-01', '2022-01-02', '2022-01-07', '2022-01-17', '2022-03-02', '2022-06-05', '2022-06-07', '2022-07-02'],
    'col1': [4, 4, 2, 2, 2, 3, 2, 1],
    'col2': [1, 2, 3, 4, 1, 3, 3, 4],
    'col3': [2, 3, 4, 4, 3, 2, 2, 1]
    }
)
date col1 col2 col3
2022-01-01 1 1 2
2022-01-02 1 2 3
2022-01-07 2 3 4
2022-01-17 2 4 1
2022-03-02 3 1 3
2022-06-05 3 2 2
2022-06-07 4 3 4
2022-07-02 4 4 1

DF按日期排序.我想创建一个列,这将给我一个计数的所有较早的行(较低的日期)与所有3列的值大于或等于当前行的值.或者换句话说:

Count rows
    where row_index < current_row_index &
          col1[row_index] >= col1[current_row_index] &
          col2[row_index] >= col2[current_row_index] &
          col3[row_index] >= col3[current_row_index]
)

结果应该如下所示:

date col1 col2 col3 ge
2022-01-01 4 1 2 0
2022-01-02 4 2 3 0
2022-01-07 2 3 4 0
2022-01-17 2 4 4 0
2022-03-02 2 1 3 3
2022-06-05 3 3 2 0
2022-06-07 2 3 2 3
2022-07-02 1 4 1 1

我试过shiftqeoverwhencum_count等各种组合,但都没能弄清楚.我也找不到一个足够相似的问题来成功地采用它的答案.有没有一种方法可以使用Polars来实现这一点?先谢谢你了.

推荐答案

您还可以使用struct将所有条件逻辑放入.cumulative_eval()

cols = "col1", "col2", "col3"

df.with_columns(ge =
   pl.struct(cols).cumulative_eval(
       pl.all_horizontal(
          pl.element().struct[col] >= pl.element().struct[col].last()
          for col in cols
       )
       .sum() - 1 # subtract 1 as we compare each row against itself
   )
)
shape: (8, 5)
┌────────────┬──────┬──────┬──────┬─────┐
│ date       ┆ col1 ┆ col2 ┆ col3 ┆ ge  │
│ ---        ┆ ---  ┆ ---  ┆ ---  ┆ --- │
│ date       ┆ i64  ┆ i64  ┆ i64  ┆ u32 │
╞════════════╪══════╪══════╪══════╪═════╡
│ 2022-01-01 ┆ 4    ┆ 1    ┆ 2    ┆ 0   │
│ 2022-01-02 ┆ 4    ┆ 2    ┆ 3    ┆ 0   │
│ 2022-01-07 ┆ 2    ┆ 3    ┆ 4    ┆ 0   │
│ 2022-01-17 ┆ 2    ┆ 4    ┆ 4    ┆ 0   │
│ 2022-03-02 ┆ 2    ┆ 1    ┆ 3    ┆ 3   │
│ 2022-06-05 ┆ 3    ┆ 3    ┆ 2    ┆ 0   │
│ 2022-06-07 ┆ 2    ┆ 3    ┆ 2    ┆ 3   │
│ 2022-07-02 ┆ 1    ┆ 4    ┆ 1    ┆ 1   │
└────────────┴──────┴──────┴──────┴─────┘

Python相关问答推荐

如何使用scipy从频谱图中回归多个高斯峰?

如何在BeautifulSoup中链接Find()方法并处理无?

Python在tuple上操作不会通过整个单词匹配

如何在箱形图中添加绘制线的传奇?

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

未删除映射表的行

如何在Python中并行化以下搜索?

如何指定列数据类型

如何使regex代码只适用于空的目标单元格

matplotlib + python foor loop

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

如何创建引用列表并分配值的Systemrame列

Gekko中基于时间的间隔约束

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

提取数组每行的非零元素

删除特定列后的所有列

高效地计算数字数组中三行上三个点之间的Angular

如何在Django查询集中生成带有值列表的带注释的字段?

如何在不遇到IndexError的情况下将基数10的整数转换为基数80?