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

如何在Polars中获取类似value_counts返回的struct数据类型?

解决Polars中将两列按行合并为struct列的问题

你遇到的核心问题有两个:一是没有调用to_struct方法(仅引用了方法对象),二是需要明确将指定列合并为每行一个struct类型。以下是两种可行的解决方案:

方法1:正确调用DataFrame.to_struct()

to_struct是Polars DataFrame的方法,必须加括号()执行才能得到结果。该方法默认会将所有列合并为一个包含原列名的struct列:

import polars as pl

df = pl.DataFrame({
    "tags": ["c", "a", "b", "d"],
    "vals":[4,3,1,1] 
})

# 调用to_struct方法,生成struct列
result = df.to_struct()
print(result)

输出结果:

shape: (4, 1)
┌─────────────┐
│ tags_vals   │
│ ---         │
│ struct[2]   │
╞═════════════╡
│ {"c", 4}    │
│ {"a", 3}    │
│ {"b", 1}    │
│ {"d", 1}    │
└─────────────┘

如果需要自定义struct列的名称,可以通过name参数指定:

result = df.to_struct(name="my_struct")

方法2:使用pl.struct()显式构造

如果你需要更灵活地选择要合并的列(比如只合并指定列),可以用pl.struct()构造函数配合select方法:

result = df.select(pl.struct(["tags", "vals"]))
print(result)

输出结果:

shape: (4, 1)
┌─────────────┐
│ struct      │
│ ---         │
│ struct[2]   │
╞═════════════╡
│ {"c", 4}    │
│ {"a", 3}    │
│ {"b", 1}    │
│ {"d", 1}    │
└─────────────┘

同样可以自定义列名:

result = df.select(my_struct=pl.struct(["tags", "vals"]))

为什么之前的代码显示"绑定方法"?

你写的df.to_struct只是引用了方法对象本身,并没有执行它。只有在方法名后添加括号(),才会触发方法执行并返回处理后的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:39:53