I'd like to create a conditional incremented column in polars.
It should start from 1 and increment only if a certain condition (pl.col('code') == 'L') is met.
import polars as pl
df = pl.DataFrame({'file': ['a.txt','a.txt','a.txt','a.txt','b.txt','b.txt','c.txt','c.txt','c.txt','c.txt','c.txt'],
                   'code': ['X','Y','Z','L','A','A','B','L','C','L','X']
                   })
df.with_columns(pl.int_range(start=1, end=pl.len()+1).over('file').alias('rrr')
                )

这会产生一个简单的无条件增量.但我如何添加条件呢?

推荐答案

我不确定您到底想要哪种输出,但下面是一个仅在满足条件的行上递增计数器的示例,使用cum_sum():

df.with_columns(
    pl.when(pl.col('code') == 'L').then(pl.lit(1)).otherwise(pl.lit(0)).alias('rrr')
).with_columns(
    pl.col('rrr').cum_sum().over('file') + 1
)

┌───────┬──────┬─────┐
│ file  ┆ code ┆ rrr │
│ ---   ┆ ---  ┆ --- │
│ str   ┆ str  ┆ i32 │
╞═══════╪══════╪═════╡
│ a.txt ┆ X    ┆ 1   │
│ a.txt ┆ Y    ┆ 1   │
│ a.txt ┆ Z    ┆ 1   │
│ a.txt ┆ L    ┆ 2   │
│ b.txt ┆ A    ┆ 1   │
│ b.txt ┆ A    ┆ 1   │
│ c.txt ┆ B    ┆ 1   │
│ c.txt ┆ L    ┆ 2   │
│ c.txt ┆ C    ┆ 2   │
│ c.txt ┆ L    ┆ 3   │
│ c.txt ┆ X    ┆ 3   │
└───────┴──────┴─────┘

Python相关问答推荐

Python 3.12中的通用[T]类方法隐式类型检索

在Python中处理大量CSV文件中的数据

对某些列的总数进行民意调查,但不单独列出每列

使可滚动框架在tkinter环境中看起来自然

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

ThreadPoolExecutor和单个线程的超时

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

多处理队列在与Forking http.server一起使用时随机跳过项目

Pandas GroupBy可以分成两个盒子吗?

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

如何使用Numpy. stracards重新编写滚动和?

使用类型提示进行类型转换

如何从比较函数生成ngroup?

如何将泛型类类型与函数返回类型结合使用?

Python:从目录内的文件导入目录

有了Gekko,可以创建子模型或将模型合并在一起吗?

替换包含Python DataFrame中的值的<;

在使用ROLING()获得最大值时,是否可以排除每个窗口中的前n个值?

关于数字S种子序列内部工作原理的困惑

删除另一个div中的特定div容器