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

Polars高效实现:根据值拼接对应列名的最优方法

高效实现Polars按行拼接值为1的列名

输入数据

abcde
01010
10000

期望输出

abcdeRESULT
01010bd
10000a

高效实现方案

避免使用map_elements的逐行循环,改用Polars原生的向量化操作,性能提升明显,以下两种方案均可:

方案1:使用pl.fold批量拼接

import polars as pl

df = pl.DataFrame({
    "a": [0, 1],
    "b": [1, 0],
    "c": [0, 0],
    "d": [1, 0],
    "e": [0, 0]
})

cols = df.columns
result_df = df.with_columns(
    pl.fold(
        acc=pl.lit(""),
        function=lambda acc, col: acc + pl.when(pl.col(col) == 1).then(col).otherwise(""),
        exprs=cols
    ).alias("RESULT")
)

方案2:使用列表拼接+空值过滤

import polars as pl

df = pl.DataFrame({
    "a": [0, 1],
    "b": [1, 0],
    "c": [0, 0],
    "d": [1, 0],
    "e": [0, 0]
})

cols = df.columns
result_df = df.with_columns(
    pl.concat_list([pl.when(pl.col(c) == 1).then(c) for c in cols])
    .list.drop_nulls()
    .str.concat("")
    .alias("RESULT")
)

方案优势

两种方案均基于Polars的向量化引擎批量处理数据,避免了map_elements带来的逐行Python循环开销,在数据量较大时性能差距会非常显著。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:40:01