Polars中select()链式调用value_counts()后用unnest()报错问题
解决Polars中
AttributeError: 'Expr' object has no attribute 'unnest'错误 问题原因
unnest()是DataFrame级别的方法,仅能对整个DataFrame调用,无法直接在select()内的表达式(Expr对象)上执行。第一个代码能正常运行,是因为你先完成select()得到DataFrame后,再调用unnest();而第二个代码试图在单个表达式后直接调用unnest(),违反了Polars的API设计规则。
解决方案
方案1:将unnest()移到select()之后执行
先在select()中保留struct类型的列,完成字段选择后,再对整个DataFrame调用unnest()拆分struct列,同时保留其他计算字段。
( df .select( pl.col("CustomerID"), # 先保留struct列,不在select内调用unnest pl.col("Country").value_counts(sort=True).struct.rename_fields(["Country", "Count"]).first().over("CustomerID").alias("Country_Stats"), Days_Since_Last_Purchase = pl.col("InvoiceDate").max() - pl.col("InvoiceDate").max().over("CustomerID"), ) .unnest("Country_Stats") # 对DataFrame调用unnest拆分struct列 .unique(maintain_order=True) )
方案2:用.struct.field()直接提取struct字段
无需使用unnest(),直接在表达式中提取struct的具体字段,可在select()内完成所有字段定义,避免后续额外操作。
# 先定义重复使用的表达式,简化代码 country_stats_expr = pl.col("Country").value_counts(sort=True).struct.rename_fields(["Country", "Count"]).first().over("CustomerID") ( df .select( pl.col("CustomerID"), country_stats_expr.struct.field("Country").alias("Country"), country_stats_expr.struct.field("Count").alias("Count"), Days_Since_Last_Purchase = pl.col("InvoiceDate").max() - pl.col("InvoiceDate").max().over("CustomerID"), ) .unique(maintain_order=True) )
方案选择建议
- 若struct包含多个字段,优先选方案1,一次
unnest()即可拆分所有字段; - 若仅需提取struct中的部分字段,或希望在
select()内完成所有字段定义,优先选方案2。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

