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
相关产品推荐
相关产品推荐

