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

如何在Python Polars中替换DataFrame的整行数据

如何将Polars DataFrame中的指定行替换为单一值?

解决方案1:通过行索引实现替换

先给DataFrame添加行索引列,针对所有列做条件判断替换后,再移除索引列:

import numpy as np
import polars as pl

df = np.zeros(shape=(4, 4))
df = pl.DataFrame(df)

# 替换索引为1的行为1.0
df = df.with_row_index().with_columns(
    pl.when(pl.col("index") == 1)
    .then(1.0)
    .otherwise(pl.col(col) for col in df.columns)
).drop("index")

print(df)

解决方案2:批量列处理(更简洁)

无需额外创建索引列,利用pl.int_range生成行号匹配目标索引,批量遍历所有列完成替换:

import numpy as np
import polars as pl

df = np.zeros(shape=(4, 4))
df = pl.DataFrame(df)

target_row = 1
replace_val = 1.0

df = df.with_columns(
    [pl.when(pl.int_range(0, pl.count()) == target_row).then(replace_val).otherwise(col) for col in df.columns]
)

print(df)

说明

Polars是列式优先的库,没有直接提供"整行替换"的API,核心思路是通过列级条件判断实现整行效果:

  • 两种方案都使用when/then/otherwise表达式,判断当前行是否为目标索引,满足条件则替换值,否则保留原数据
  • 方案2无需额外操作索引列,适配任意列数的DataFrame

运行后输出结果符合预期:

┌──────────┬──────────┬──────────┬──────────┐
│ column_0 ┆ column_1 ┆ column_2 ┆ column_3 │
│ ---      ┆ ---      ┆ ---      ┆ ---      │
│ f64      ┆ f64      ┆ f64      ┆ f64      │
╞══════════╪══════════╪══════════╪══════════╡
│ 0.0      ┆ 0.0      ┆ 0.0      ┆ 0.0      │
│ 1.0      ┆ 1.0      ┆ 1.0      ┆ 1.0      │
│ 0.0      ┆ 0.0      ┆ 0.0      ┆ 0.0      │
│ 0.0      ┆ 0.0      ┆ 0.0      ┆ 0.0      │
└──────────┴──────────┴──────────┴──────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:05:16