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

Polars列操作疑问:如何用N列值更新Survivors与Deaths列

Polars DataFrame列替换的正确实现方法

Polars 中的 DataFrame 是不可变数据结构,不支持像 Pandas 那样通过索引直接赋值修改列,这就是你触发错误的原因。必须使用 with_columns 方法来创建或替换列,以下是两种可行的实现方式:

方法1:直接使用乘法运算符

import polars as pl

# 替换Survivors和Deaths列
table = table.with_columns(
    (pl.col("Survivors") * pl.col("N")).alias("Survivors"),
    (pl.col("Deaths") * pl.col("N")).alias("Deaths")
)

方法2:使用mul方法(更具可读性)

table = table.with_columns(
    pl.col("Survivors").mul(pl.col("N")).alias("Survivors"),
    pl.col("Deaths").mul(pl.col("N")).alias("Deaths")
)

注意:with_columns 会返回一个新的 DataFrame,需要将结果重新赋值给原变量才能保留修改。Polars 这种 immutable 设计是为了避免原地修改带来的意外副作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:31:17