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

如何在Polars中查找每行最右侧的非null数据?

如何在Polars中查找每行最右侧的非null数据?

给定如下Polars DataFrame:

import polars as pl

data_df = pl.from_repr("""
┌──────┬──────┬──────┬──────┐
│ d1   ┆ d2   ┆ d3   ┆ d4   │
│ ---  ┆ ---  ┆ ---  ┆ ---  │
│ i64  ┆ i64  ┆ i64  ┆ i64  │
╞══════╪══════╪══════╪══════╡
│ 20   ┆ 37   ┆ 48   ┆ 50   │
│ 31   ┆ 15   ┆ 4    ┆ null │
│ 56   ┆ 27   ┆ null ┆ null │
│ 44   ┆ 36   ┆ 88   ┆ 9    │
│ 10   ┆ null ┆ null ┆ null │
│ null ┆ null ┆ null ┆ null │
└──────┴──────┴──────┴──────┘
""")

我们需要添加一个result列,取值为每行最右侧的非null值,整行均为null时result为null。

解决方案

利用Polars的coalesce函数结合列反转实现:coalesce会返回传入表达式中第一个非null值,将列从右到左传入后,就能拿到原行最右侧的非null值。

代码实现:

result_df = data_df.with_columns(
    pl.coalesce(pl.all().reverse()).alias("result")
)

print(result_df)

输出结果

运行后得到符合预期的结果:

┌──────┬──────┬──────┬──────┬────────┐
│ d1   ┆ d2   ┆ d3   ┆ d4   ┆ result │
│ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---    │
│ i64  ┆ i64  ┆ i64  ┆ i64  ┆ i64    │
╞══════╪══════╪══════╪══════╪════════╡
│ 20   ┆ 37   ┆ 48   ┆ 50   ┆ 50     │
│ 31   ┆ 15   ┆ 4    ┆ null ┆ 4      │
│ 56   ┆ 27   ┆ null ┆ null ┆ 27     │
│ 44   ┆ 36   ┆ 88   ┆ 9    ┆ 9      │
│ 10   ┆ null ┆ null ┆ null ┆ 10     │
│ null ┆ null ┆ null ┆ null ┆ null   │
└──────┴──────┴──────┴──────┴────────┘

说明

  • pl.all()获取所有列,reverse()将列顺序反转(原列顺序d1,d2,d3,d4变为d4,d3,d2,d1)
  • coalesce遍历反转后的列,返回第一个非null值,对应原行最右侧的非null值
  • 若整行都是null,coalesce会返回null,满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:38:35