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

如何在Polars DataFrame中基于多条件添加同一新列?

Polars DataFrame 添加标签列的正确实现方式

你遇到的重复列错误,是因为在同一个with_columns调用里,两次定义了名为label的列,Polars不允许添加重复名称的列。

正确的做法是把多个条件合并到单个when-then链式调用中,最终只生成一个label列:

df.with_columns(
    pl.when(~pl.col("temp").is_null().all() & pl.col("daily_temp").is_null().all())
      .then("sensor_1_" + pl.col("location"))
      .when(pl.col("temp").is_null().all() & ~pl.col("daily_temp").is_null().all())
      .then("sensor_2_" + pl.col("location"))  # 注意统一字段名,原代码中"loc"和"location"需保持一致
      # 可选:添加默认值处理不符合任何条件的行
      .otherwise(pl.lit("unknown"))
      .alias("label")
)

关键说明:

  • 链式when-then会按顺序匹配条件,第一个满足的条件会为该行赋值
  • 注意字段名一致性:原代码中第一个条件用location,第二个用loc,需确保是同一个字段名,避免报错
  • 关于pl.all():如果你的需求是每行判断temp/daily_temp是否为null(而非整列全为null),需要去掉.all(),改为直接用pl.col("temp").is_null()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:22:01