如何在Polars中根据列名提取值并生成新列?
在Polars中根据另一列的列名填充新列值
问题场景
现有Polars DataFrame如下:
import polars as pl df = pl.from_repr(""" ┌────────┬─────────┬────────┬─────┬──────────┐ │ Name ┆ Average ┆ Median ┆ Q1 ┆ Variable │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 ┆ str │ ╞════════╪═════════╪════════╪═════╪══════════╡ │ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Average │ │ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Median │ │ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Q1 │ │ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Average │ │ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Median │ │ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Q1 │ └────────┴─────────┴────────┴─────┴──────────┘ """)
需要新增value列,根据Variable列的内容,提取对应列(Average/Median/Q1)的数值,最终得到目标结果。
尝试过df = df.with_columns(value = pl.col(f"{pl.col.variable}"))无法生效,转置DataFrame成本高且不符合需求。
可行方案
方案1:动态列选择+coalesce
生成目标列的筛选列表,通过coalesce合并结果,自动匹配每行的Variable值:
df = df.with_columns( value=pl.coalesce( [pl.col(col).filter(pl.col("Variable") == col) for col in ["Average", "Median", "Q1"]] ) )
方案2:用pl.row()按名称提取
通过row(by_name=True)获取每行的键值对,直接根据Variable的取值提取对应值:
df = df.with_columns( value=pl.row(by_name=True).map(lambda row: row[row["Variable"]]) )
方案3:分支判断(适合枚举值少的场景)
如果Variable的可能值有限,直接用when/then分支匹配:
df = df.with_columns( value=pl.when(pl.col("Variable") == "Average") .then(pl.col("Average")) .when(pl.col("Variable") == "Median") .then(pl.col("Median")) .when(pl.col("Variable") == "Q1") .then(pl.col("Q1")) )
内容的提问来源于stack exchange,提问作者user24758287
相关产品推荐
相关产品推荐

