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

Polars DataFrame:如何基于另一列匹配条件一行代码更新列?

Polars 中基于另一列条件更新列的简洁实现

针对你需要的「当col2值为a时,将col1对应元素乘以1000」的需求,完全不需要用循环遍历,下面提供两种符合要求的简洁实现:

方案1:Polars 原生向量化实现(推荐,高效)

这是Polars官方推荐的方式,利用向量化操作批量处理,性能远优于循环和逐行lambda:

import polars as pl

df = pl.DataFrame({
    'col1':[1,2,3,4],
    'col2':['a', 'a', 'b', 'b'], 
    'col3':[10.9, 12.0, 33.3, 34.4]
})

# 一行代码完成更新
df = df.with_columns(pl.when(pl.col('col2') == 'a').then(pl.col('col1') * 1000).otherwise(pl.col('col1')).alias('col1'))

print(df)

方案2:借助 Lambda 实现(满足需求中的lambda要求)

如果必须借助lambda,可以通过map_elements逐行处理(注意:逐行处理性能低于向量化,仅适合简单场景):

import polars as pl

df = pl.DataFrame({
    'col1':[1,2,3,4],
    'col2':['a', 'a', 'b', 'b'], 
    'col3':[10.9, 12.0, 33.3, 34.4]
})

# 借助lambda的一行更新代码
df = df.with_columns(pl.struct(['col1', 'col2']).map_elements(lambda row: row['col1'] * 1000 if row['col2'] == 'a' else row['col1']).alias('col1'))

print(df)

输出结果

两种方案都会得到和你原来循环实现一致的输出:

shape: (4, 3)
┌────────┬──────┬──────┐
│ col1   ┆ col2 ┆ col3 │
│ ---    ┆ ---  ┆ ---  │
│ f64    ┆ str  ┆ f64  │
╞════════╪══════╪══════╡
│ 1000.0 ┆ a    ┆ 10.9 │
│ 2000.0 ┆ a    ┆ 12.0 │
│ 3.0    ┆ b    ┆ 33.3 │
│ 4.0    ┆ b    ┆ 34.4 │
└────────┴──────┴──────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:04:54