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

如何基于Polars中其他列的部分名称创建新列?

解决方案

直接用Polars的向量化操作实现,比循环更高效,适合处理多列场景:

import polars as pl

df = pl.from_repr("""
┌─────┬──────┬──────┬──────┬──────┐
│ id  ┆ hcc1 ┆ hcc2 ┆ hcc5 ┆ hcc8 │
│ --- ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
│ i64 ┆ i64  ┆ i64  ┆ i64  ┆ i64  │
╞═════╪══════╪══════╪══════╪══════╡
│ 1   ┆ 0    ┆ 0    ┆ 0    ┆ 1    │
│ 2   ┆ 1    ┆ 0    ┆ 1    ┆ 0    │
│ 3   ┆ 1    ┆ 1    ┆ 1    ┆ 0    │
└─────┴──────┴──────┴──────┴──────┘
""")

# 筛选所有hcc开头的列
hcc_cols = [col for col in df.columns if col.startswith("hcc")]

# 构建hccall列的表达式
hccall_expr = (
    pl.concat_list(
        [pl.when(pl.col(col) == 1).then(col.lstrip("hcc")).otherwise(None) for col in hcc_cols]
    )
    .list.filter(lambda x: x.is_not_null())  # 过滤掉值为0对应的空值
    .str.join(",")  # 用逗号拼接列表元素
)

# 添加新列并保留id列
result = df.select("id", hccall=hccall_expr)
print(result)

代码说明

  1. 筛选hcc列:用列表推导式从DataFrame列名中提取所有以hcc开头的列,自动适配你50多列的场景。
  2. 生成条件表达式:对每个hcc列,判断值是否为1,是则提取列名中hcc后的数字部分,否则返回None。
  3. 拼接字符串:把所有条件表达式的结果合并成列表,过滤掉空值后,用逗号连接成字符串,得到最终的hccall列。

运行后输出和你期望的结果一致:

shape: (3, 2)
┌─────┬────────┐
│ id  ┆ hccall │
│ --- ┆ ---    │
│ i64 ┆ str    │
╞═════╪════════╡
│ 1   ┆ 8      │
│ 2   ┆ 1,5    │
│ 3   ┆ 1,2,5  │
└─────┴────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:03:17