本文介紹了如何在 Polars DataFrame 的每個窗口(分組)內(nèi)添加行號。通過結(jié)合 int_range() 函數(shù)和窗口函數(shù),可以方便地為每個分組生成連續(xù)的行號,從而實現(xiàn)更靈活的數(shù)據(jù)分析和處理。
在 Polars 中,雖然 with_row_numbers() 方法可以為整個 DataFrame 添加行號,但有時我們需要在特定的窗口(分組)內(nèi)添加行號,以便進(jìn)行更細(xì)粒度的數(shù)據(jù)分析。本文將介紹如何利用 Polars 的窗口函數(shù)和 int_range() 函數(shù)來實現(xiàn)這一目標(biāo)。
核心思路:
核心思路是使用 pl.int_range(pl.len()) 生成一個從 0 開始,長度等于組大小的整數(shù)序列,然后將其加 1,使其成為從 1 開始的行號。再通過 over("groupings") 將此操作應(yīng)用于每個分組窗口內(nèi)。
具體實現(xiàn):
以下是一個示例,演示了如何在 DataFrame 的每個分組內(nèi)添加行號:
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)
代碼解釋:
pl.int_range(pl.len()): pl.len() 返回當(dāng)前分組的大小。pl.int_range() 則生成一個從 0 開始,長度等于分組大小的整數(shù)序列。例如,如果一個分組有 3 行,則 pl.int_range(pl.len()) 將生成 [0, 1, 2]。
1 + pl.int_range(pl.len()): 將生成的整數(shù)序列加 1,使其從 1 開始,作為行號。 在上述例子中,就變成了 [1, 2, 3]。
.over("groupings"): 這是一個窗口函數(shù)。它指定了將上述操作應(yīng)用于哪個分組。在這個例子中,我們按照 "groupings" 列進(jìn)行分組,并在每個分組內(nèi)應(yīng)用上述操作。
df.with_columns(count = ...): 使用 with_columns() 方法將新生成的 "count" 列添加到 DataFrame 中。
運行結(jié)果:
運行上述代碼將得到以下 DataFrame:
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 │ └───────────┴───────────────────────────┴───────┘
可以看到,"count" 列包含了每個分組內(nèi)的行號。
注意事項:
總結(jié):
通過結(jié)合 int_range() 函數(shù)和窗口函數(shù),可以方便地在 Polars DataFrame 的每個分組內(nèi)添加行號。這種方法靈活且高效,可以滿足各種數(shù)據(jù)分析需求。 掌握這種技巧,能夠更方便地進(jìn)行分組統(tǒng)計、排名等操作。
以上就是Polars DataFrame 中如何在窗口內(nèi)添加行號的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進(jìn)程會占用資源并降低性能。幸運的是,許多工具可以讓 Windows 保持平穩(wěn)運行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號