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

如何用Polars实现Pandas中groupby转置转字典的等效操作

在Polars中实现Pandas的groupby后转置转字典操作

原始数据

首先是你提供的Polars DataFrame:

import polars as pl
df = pl.DataFrame({
    'index': [1,2,3,2,1],
    'object': [1, 1, 1, 2, 2],
    'period': [1, 2, 4, 4, 23],
    'value': [24, 67, 89, 5, 23]
})

目标效果

你需要实现和以下Pandas代码等价的功能,得到以原index值为键、对应分组最后一行数据为值的字典:

df.to_pandas().groupby("index").last().transpose().to_dict()

输出结果:

{1: {'object': 2, 'period': 23, 'value': 23},
 2: {'object': 2, 'period': 4, 'value': 5},
 3: {'object': 1, 'period': 4, 'value': 89}}

Polars实现方案

直接通过分组聚合+字典推导式就能完成,不需要额外转置操作:

# 按index分组,提取每组所有列的最后一行数据
grouped_df = df.group_by("index", maintain_order=True).agg(pl.all().last())

# 转换为目标格式的字典
result = {row["index"]: row.drop("index").to_dict() for row in grouped_df.iter_rows(named=True)}

print(result)

代码说明

  1. 分组聚合:group_by("index", maintain_order=True)按index列分组并保持原始顺序,.agg(pl.all().last())对每组的所有列取最后一个值,得到每个分组的最终行数据。
  2. 字典转换:iter_rows(named=True)遍历分组后的每行带列名数据,通过字典推导式将index值作为键,去掉index列后的行数据转为字典作为值,完美匹配目标格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:54:17