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

如何无需显式转换Pandas Series,按值分组并返回索引列表字典?

问题:Pandas Series按值分组生成索引列表字典

我有一个如下所示的Pandas Series:

import numpy as np
import string
import pandas as pd

np.random.seed(0)
data = np.random.randint(1,6,10)
index = list(string.ascii_lowercase)[:10]
a = pd.Series(data=data,index=index,name='apple')

输出的Series为:

a    5
b    1
c    4
d    4
e    4
f    2
g    4
h    3
i    5
j    1
Name: apple, dtype: int32

我希望按Series的值进行分组,返回一个以值为键、对应索引列表为值的字典,目标结果如下:

{1: ['b', 'j'], 2: ['f'], 3: ['h'], 4: ['c', 'd', 'e', 'g'], 5: ['a', 'i']}

我当前的实现方式如下:

b = a.reset_index().set_index('apple').squeeze()
grouped = b.groupby(level=0).apply(list).to_dict()

但这种先显式转换Series的方式不够Pythonic,请问是否可以通过单个函数或链式调用一行代码实现该需求?


解决方案

可以通过链式调用一行代码实现,无需显式转换中间变量,更符合Pythonic风格:

grouped = a.groupby(a).apply(lambda x: x.index.tolist()).to_dict()

代码解释:

  • a.groupby(a):直接以原Series的值作为分组依据,对Series进行分组
  • apply(lambda x: x.index.tolist()):对每个分组,提取其索引并转换为列表
  • to_dict():将分组后的结果直接转为目标格式的字典

另外,也可以通过reset_index配合agg实现可读性更强的链式调用:

grouped = a.reset_index().groupby('apple')['index'].agg(list).to_dict()

这种方式通过reset_index将原索引转为普通列,再按apple列分组,对index列聚合为列表后转字典,逻辑更直观。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:15:42