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

使用Polars的list.eval时如何创建struct类型列?

问题解答

错误原因

你遇到的TypeError是因为pl.struct()不支持直接传递字典作为单个位置参数。pl.struct()需要接收关键字参数(即key=value形式),或多个列表达式作为参数,而非字典对象。

惯用解决方法

在list.eval中生成struct类型的列表列,正确的惯用写法是直接给pl.struct()传入关键字参数,无需重复调用list.eval或依赖map_elements:

import polars as pl

# 初始DataFrame
df = pl.DataFrame(
    [
        pl.Series("start", ["2023-01-01"]).str.to_date(),
        pl.Series("end", ["2024-01-01"]).str.to_date(),
    ]
)

# 生成日期范围列
df = df.with_columns(
    pl.date_ranges(pl.col("start"), pl.col("end"), "1mo", closed="left").alias("date_range")
)

# 正确生成包含struct的列表列
df = df.with_columns(
    pl.col("date_range")
    .list.eval(
        pl.struct(
            year=pl.element().dt.year(),
            month=pl.element().dt.month()
        )
    )
    .alias("years_months")
)

print(df)

输出结果

shape: (1, 4)
┌────────────┬────────────┬─────────────────────────────────┬─────────────────────────────────┐
│ start      ┆ end        ┆ date_range                      ┆ years_months                    │
│ ---        ┆ ---        ┆ ---                             ┆ ---                             │
│ date       ┆ date       ┆ list[date]                      ┆ list[struct[2]]                 │
╞════════════╪════════════╪═════════════════════════════════╪═════════════════════════════════╡
│ 2023-01-01 ┆ 2024-01-01 ┆ [2023-01-01, 2023-02-01, … 202… ┆ [{2023, 1}, {2023, 2}, … {2023… │
└────────────┴────────────┴─────────────────────────────────┴─────────────────────────────────┘

动态字段场景的写法

如果需要通过字典动态定义struct字段(比如字段名或逻辑是动态生成的),可以用字典解包的方式传入,兼顾灵活性与API规范:

struct_fields = {
    "year": pl.element().dt.year(),
    "month": pl.element().dt.month()
}

df = df.with_columns(
    pl.col("date_range")
    .list.eval(pl.struct(**struct_fields))
    .alias("years_months")
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:50:09