
本文介绍了如何在Polars DataFrame中使用窗口函数为每个分组添加行号。通过结合`int_range()`函数和`over()`方法,可以轻松地在每个窗口内生成递增的序列,从而实现分组行号的功能。本文提供详细的代码示例和解释,帮助读者理解并掌握该技巧。
在数据分析中,经常需要在每个分组内添加行号,以便进行后续的计算或分析。Polars 提供了强大的窗口函数功能,可以方便地实现这一需求。本文将详细介绍如何使用 Polars 的窗口函数和 int_range() 函数,为 DataFrame 中的每个分组添加行号。
核心思路
核心思路是利用 pl.int_range(pl.len()) 在每个分组内生成一个从 0 开始的整数序列,然后通过窗口函数 over("groupings") 将其应用到每个分组。最后,加 1 即可得到从 1 开始的行号。
具体实现
下面是一个具体的代码示例:
import polars as pl
df = pl.DataFrame([
    {'groupings': 'a', 'target_count_over_windows': 1},
    {'groupings': 'a', 'target_count_over_windows': 2},
    {'groupings': 'a', 'target_count_over_windows': 3},
    {'groupings': 'b', 'target_count_over_windows': 1},
    {'groupings': 'c', 'target_count_over_windows': 1},
    {'groupings': 'c', 'target_count_over_windows': 2},
    {'groupings': 'd', 'target_count_over_windows': 1},
    {'groupings': 'd', 'target_count_over_windows': 2},
    {'groupings': 'd', 'target_count_over_windows': 3}
])
df = df.with_columns(count = 1 + pl.int_range(pl.len()).over("groupings"))
print(df)代码解释
运行结果
运行上述代码,将得到以下结果:
shape: (9, 3) ┌───────────┬───────────────────────────┬───────┐ │ groupings ┆ target_count_over_windows ┆ count │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═══════════╪═══════════════════════════╪═══════╡ │ a ┆ 1 ┆ 1 │ │ a ┆ 2 ┆ 2 │ │ a ┆ 3 ┆ 3 │ │ b ┆ 1 ┆ 1 │ │ c ┆ 1 ┆ 1 │ │ c ┆ 2 ┆ 2 │ │ d ┆ 1 ┆ 1 │ │ d ┆ 2 ┆ 2 │ │ d ┆ 3 ┆ 3 │ └───────────┴───────────────────────────┴───────┘
可以看到,DataFrame 中成功添加了 count 列,其中包含了每个分组内的行号。
注意事项
总结
本文介绍了如何使用 Polars 的窗口函数和 int_range() 函数,为 DataFrame 中的每个分组添加行号。该方法简单易懂,效率高,适用于各种数据分析场景。通过掌握该技巧,可以更加方便地进行分组计算和分析。
以上就是Polars窗口函数内添加行号的实用指南的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号