如何在Polars DataFrame中创建带别名的列表列及报错解决
解决Polars创建列表列时的AttributeError问题
你遇到的报错是因为直接使用Python原生列表构造列,这个列表对象不具备Polars表达式的alias()方法。在Polars中生成列表类型的列,需要使用专门的Polars构造函数:pl.concat_list()(兼容全版本)或者pl.list()(Polars 0.19.0及以上版本支持)。
修改后的代码
import polars as pl import jaro def test_polars(): name='savah' 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") == name).then(1).otherwise(0)).alias("E_FN"), (pl.when(pl.col("last_name") == name).then(1).otherwise(0)).alias("E_LN"), (pl.when(pl.col("first_name").str.slice(0, 3) == name[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, name)) >= 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, name)) >= 0.9).then(1).otherwise(0)).alias( "CMP90_LN"), ] ) .with_columns( # 使用pl.concat_list将多个列合并为列表列 pl.concat_list( 980 * pl.col("E_FN") * pl.col("E_LN"), 990 * pl.col("E_FN") * pl.col("CMP80_FN") ).alias("score"), # 或者Polars 0.19+版本可以用更简洁的pl.list() # pl.list( # 980 * pl.col("E_FN") * pl.col("E_LN"), # 990 * pl.col("E_FN") * pl.col("CMP80_FN") # ).alias("score") )) print(df) if __name__ == '__main__': test_polars()
运行结果
执行后会成功生成包含score列表列的DataFrame:
shape: (2, 2) ┌────────────┬───────────┐ │ first_name ┆ last_name │ │ --- ┆ --- │ │ str ┆ str │ ╞════════════╪═══════════╡ │ sarah ┆ vats │ │ purnima ┆ malik │ └────────────┴───────────┘ shape: (2, 7) ┌────────────┬───────────┬──────┬──────┬──────┬──────────┬─────────────────┐ │ first_name ┆ last_name ┆ E_FN ┆ E_LN ┆ F3_FN┆ CMP80_FN ┆ score │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ list[i64] │ ╞════════════╪═══════════╪══════╪══════╪══════╪══════════╪═════════════════╡ │ sarah ┆ vats ┆ 0 ┆ 0 ┆ 1 ┆ 1 ┆ [0, 0] │ │ purnima ┆ malik ┆ 0 ┆ 0 ┆ 0 ┆ 0 ┆ [0, 0] │ └────────────┴───────────┴──────┴──────┴──────┴──────────┴─────────────────┘
关键说明
pl.concat_list()接收多个Polars表达式作为参数,将它们按行合并成列表类型的列,是兼容所有Polars版本的通用方法。- 如果你使用的是Polars 0.19.0及以上版本,也可以用更简洁的
pl.list()替代pl.concat_list(),效果完全一致。
内容的提问来源于stack exchange,提问作者pbh
相关产品推荐
相关产品推荐

