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

如何在Rust Polars中识别所有值均非空的行?

在Rust的Polars中识别所有值均为非空的行

你可以通过Rust版Polars提供的all_horizontal函数实现需求,逻辑和Python端完全一致,以下是完整示例:

use polars::prelude::*;

fn main() -> Result<(), PolarsError> {
    // 构造含空值的DataFrame
    let df = DataFrame::new(vec![
        Series::new("a", &[Some(1), None, None, Some(1)]),
        Series::new("b", &[None, Some(1), None, Some(1)]),
    ])?;

    // 生成标识每行全非空的ChunkedArray<bool>
    let all_non_null = df
        .select([all_horizontal(all().is_not_null())])?
        .column(0)?
        .bool()?
        .clone();

    // 输出结果
    println!("{:?}", all_non_null);
    Ok(())
}

代码说明

  • all().is_not_null():生成所有列的非空判断表达式,每个列对应一个布尔序列,标记该行该列是否非空。
  • all_horizontal(...):横向聚合这些布尔表达式,返回一个新的布尔序列,每行的值为对应行所有列非空判断的逻辑与结果(即所有列都非空时为true)。
  • 最后通过column(0)取出结果列,转为ChunkedArray<bool>类型,就是你需要的标识数组。

手动实现方式(可选)

如果需要更底层的手动遍历逻辑,可以通过fold累积每列的非空判断结果:

use polars::prelude::*;

fn main() -> Result<(), PolarsError> {
    let df = DataFrame::new(vec![
        Series::new("a", &[Some(1), None, None, Some(1)]),
        Series::new("b", &[None, Some(1), None, Some(1)]),
    ])?;

    let all_non_null = df
        .columns()
        .iter()
        .map(|series| series.is_not_null())
        .fold(
            // 初始化全为true的数组
            Ok(ChunkedArray::full("all_non_null", true, df.height())),
            // 依次与每列的非空判断做逻辑与
            |acc, ca| acc.and(&ca),
        )?;

    println!("{:?}", all_non_null);
    Ok(())
}

两种方式的输出结果一致,都会得到:

[false, false, false, true]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:03:25