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

如何在Polars DataFrame的列表类型列中查找最大值?

问题解决:Polars中计算列表列的行内最大值

错误原因

你用pl.max(pl.col("score"))报错的核心原因是:pl.max()是全局聚合函数,仅接受列名字符串作为参数,不能直接传入表达式对象(pl.col("score")属于Expr类型)。要计算每行中score列表的元素最大值,需要调用列表达式的.max()方法——这是行内的元素级操作,专门处理列表类型的列。

修改后的代码

将获取max_score的代码段替换为pl.col("score").max().alias("max_score")即可正常运行:

import polars as pl
import jaro


def test_polars():
    fname='sarah'
    lname = 'vatssss'
    data = {"first_name": ['sarah', 'purnima'], "last_name": ['vats', 'malik']}
    df = pl.DataFrame(data)
    print(df)
    df = (df.with_columns(
        [
            (pl.when(pl.col("first_name") == fname).then(1).otherwise(0)).alias("E_FN"),
            (pl.when(pl.col("last_name") == lname).then(1).otherwise(0)).alias("E_LN"),
            (pl.when(pl.col("first_name").str.slice(0, 3) == fname[0:3]).then(1).otherwise(0)).alias("F3_FN"),
            (pl.when(pl.col("first_name").map_elements(
                lambda first_name: jaro.jaro_winkler_metric(first_name, fname)) >= 0.8).then(1).otherwise(0)).alias(
                "CMP80_FN"),
            (pl.when(pl.col("last_name").map_elements(
                lambda last_name: jaro.jaro_winkler_metric(last_name, lname)) >= 0.9).then(1).otherwise(0)).alias(
                "CMP90_LN"),

        ]
    )
    .with_columns(
        pl.concat_list(980 * pl.col("E_FN"), 970 * pl.col("E_LN")).alias("score")
    )
    .with_columns(
        pl.col("score").max().alias("max_score")
    )
    )

    print(df)


if __name__ == '__main__':
    test_polars()

额外优化建议

Polars优先推荐向量化操作,map_elements是逐行处理,效率较低。可以直接用Polars原生的str.jaro_winkler函数计算相似度,无需依赖第三方库:

# 替换原代码中的CMP80_FN和CMP90_LN计算逻辑
(pl.when(pl.col("first_name").str.jaro_winkler(fname) >= 0.8).then(1).otherwise(0)).alias("CMP80_FN"),
(pl.when(pl.col("last_name").str.jaro_winkler(lname) >= 0.9).then(1).otherwise(0)).alias("CMP90_LN"),

这样代码更简洁,执行效率也更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:46:15