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

如何在Python的Polars DataFrame中用列表值条件更新列?

在Python Polars中实现类似Pandas .loc[]的条件行更新

在Polars中要实现按筛选顺序用列表/Series值条件更新列,核心是要让新值和筛选出的行一一对应,下面是两种最实用的方法:

方法一:临时行索引+合并(最贴近Pandas .loc逻辑)

通过给原DataFrame添加临时行索引,将新值与筛选行的索引绑定后合并回原表,确保顺序完全对齐:

import polars as pl

# 示例数据
df = pl.DataFrame({
    "Season": [2022, 2023, 2023, 2023, 2023, 2023, 2024],
    "Wk": [10, 1, 2, 3, 4, 5, 2],
    "Value": [1, 2, 3, 4, 5, 6, 7]
})

# 要更新的新值(必须和筛选结果的行数、顺序完全匹配)
new_values = [10, 20, 30, 40, 50]

# 1. 给原表添加临时行索引
df_with_idx = df.with_row_index("temp_idx")

# 2. 筛选符合条件的行,提取它们的索引并和新值组成更新表
filtered_rows = df_with_idx.filter((pl.col("Season") == 2023) & (pl.col("Wk") <= 5))
update_df = pl.DataFrame({
    "temp_idx": filtered_rows["temp_idx"],
    "Value": new_values
})

# 3. 左合并更新表,用fill_null保留原列的非目标行值,最后清理临时列
df_updated = df_with_idx.join(update_df, on="temp_idx", how="left") \
    .with_columns(pl.col("Value_right").fill_null(pl.col("Value_left")).alias("Value")) \
    .drop(["temp_idx", "Value_left", "Value_right"])

print(df_updated)

方法二:when+then结合行号匹配(无需临时索引)

如果新值是Polars Series,可以通过筛选后的行号来定位新值,直接构造更新列:

import polars as pl

# 示例数据同方法一
df = pl.DataFrame({
    "Season": [2022, 2023, 2023, 2023, 2023, 2023, 2024],
    "Wk": [10, 1, 2, 3, 4, 5, 2],
    "Value": [1, 2, 3, 4, 5, 6, 7]
})

new_values = pl.Series([10, 20, 30, 40, 50])

# 构造更新逻辑:用筛选后的行号匹配新值位置
df_updated = df.with_columns(
    pl.when((pl.col("Season") == 2023) & (pl.col("Wk") <= 5))
      .then(new_values[pl.int_range(0, pl.count()).filter((pl.col("Season") == 2023) & (pl.col("Wk") <= 5))])
      .otherwise(pl.col("Value"))
      .alias("Value")
)

print(df_updated)

注意事项

  • 直接用when().then(列表)会失效:因为Polars的向量化操作会把列表当成整个列的常量,不会按筛选行顺序对应。
  • 新值的长度必须和筛选出的行数完全一致,否则会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:53:24