You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars如何用窗口函数按组填充空值(每组仅一个有效值)

在Polars中用窗口函数填充分组空值

针对每组仅含一个非空有效值、其余为Null的分组数据集,优先用窗口函数实现空值填充的方案如下:

方法1:first()窗口函数(高效适配场景)

因为每组只有一个有效值,直接通过first(ignore_nulls=True)提取分组内的唯一非空值,结合.over()指定分组列即可完成填充。

示例代码:

import polars as pl

# 构造测试数据集
df = pl.DataFrame({
    "group": ["A", "A", "A", "B", "B", "B"],
    "value": [None, 10, None, 20, None, None]
})

# 执行空值填充
filled_df = df.with_columns(
    pl.col("value").first(ignore_nulls=True).over("group").alias("filled_value")
)

print(filled_df)

输出结果:

shape: (6, 3)
┌───────┬───────┬──────────────┐
│ group ┆ value ┆ filled_value │
│ ---   ┆ ---   ┆ ---          │
│ str   ┆ i64   ┆ i64          │
╞═══════╪═══════╪══════════════╡
│ A     ┆ null  ┆ 10           │
│ A     ┆ 10    ┆ 10           │
│ A     ┆ null  ┆ 10           │
│ B     ┆ 20    ┆ 20           │
│ B     ┆ null  ┆ 20           │
│ B     ┆ null  ┆ 20           │
└───────┴───────┴──────────────┘

方法2:ffill()+bfill()窗口函数(对齐Pandas思路)

和Pandas的处理逻辑一致,通过分组内的向前填充+向后填充覆盖空值,适合扩展到组内多有效值的场景。

示例代码:

filled_df = df.with_columns(
    pl.col("value").ffill().over("group").bfill().over("group").alias("filled_value")
)

内容的提问来源于stack exchange,提问作者steven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:40:02