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

Polars中行级更新实现:无需依赖列名与列数

Polars 无依赖列名/列数的行级更新实现

原始DataFrame

先创建示例DataFrame:

import polars as pl

df = pl.DataFrame([[1,2,3],[4,5,6],[7,8,9]], list('abc'))

输出如下:

shape: (3, 3)
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1   ┆ 4   ┆ 7   │
│ 2   ┆ 5   ┆ 8   │
│ 3   ┆ 6   ┆ 9   │
└─────┴─────┴─────┘

1. 替换指定整行(第二行)

通过动态获取列名+行索引定位,无需硬编码列名。这里目标行是索引为1的行(Polars行索引从0开始),替换为[43,42,41]:

target_row_values = [43, 42, 41]

# 动态遍历所有列,对目标行赋值
df_updated_row = df.with_columns(
    pl.col(col_name).when(pl.row_index() == 1).then(pl.lit(val)).otherwise(pl.col(col_name))
    for col_name, val in zip(df.columns, target_row_values)
)

运行后输出:

shape: (3, 3)
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1   ┆ 4   ┆ 7   │
│ 43  ┆ 42  ┆ 41  │
│ 3   ┆ 6   ┆ 9   │
└─────┴─────┴─────┘

2. 按条件替换指定行的列值

针对第二行中大于4的数值取反,通过行索引+列条件实现,无需依赖列名:

df_conditional_update = df.with_columns(
    pl.all().when((pl.row_index() == 1) & (pl.col(pl.int64) > 4)).then(-pl.col(pl.int64)).otherwise(pl.col(pl.int64))
)

运行后输出:

shape: (3, 3)
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1   ┆ 4   ┆ 7   │
│ 2   ┆ -5  ┆ -8  │
│ 3   ┆ 6   ┆ 9   │
└─────┴─────┴─────┘

关键说明

  • 用pl.row_index()定位目标行,仅需指定行索引位置
  • pl.all()选中所有列,适配任意列数场景
  • 动态遍历列名或使用pl.all(),完全避免依赖具体列名(如a/b/c)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:37:40