Skip to main content
 首页 » 编程设计

python之数据框到按键分组的元组列表的字典

2025年05月04日9dudu

我有一个数据框 df,它看起来如下:

        a    b    c    d 
0       8    xx   17   1.0   
1       8    xy   19   1.0  
2       8    zz   13   0.0 
3       9    tt   8    5.0 

我正在尝试创建一个字典,其中包含一个包含元组列表的键 像下面这样:

{8:[(17,1.0),(19,1.0),(13,0.0)], 9:[(8,5.0)]}  

这里,key来自a列,元组列表是key为a的c列和d列。我也在将其应用于其他数据集并尝试过

df_new = df.groupby(['a'])[['c','d']).apply(lambda x: [tuple(x) for x in x.values]) 

但是,我总是报错

raise TypeError('Series.name must be a hashable type') 
TypeError: Series.name must be a hashable type 

我尝试删除 groupby 中的 ['a'] 并将其保留为 'a',如下所示:

df_new = df.groupby('a')[['c','d']).apply(lambda x: [tuple(x) for x in x.values]) 

但是,我得到了同样的以下错误:

raise TypeError('Series.name must be a hashable type') 
TypeError: Series.name must be a hashable type 

我不想让原始数据帧 df 中的所有内容都不可变。我想保持原样。

有没有办法使用 pandas 功能来完成此操作?我真的不想制作列表,然后通过它们的索引将一些列表压缩在一起并从中创建一个字典。

请您参考如下方法:

使用 defaultdict

from collections import defaultdict 
 
d = defaultdict(list) 
for tup in df.itertuples(): 
    d[tup.a].append((tup.c, tup.d)) 
 
dict(d) 
 
{8: [(17, 1.0), (19, 1.0), (13, 0.0)], 9: [(8, 5.0)]} 

*使用to_dict 和groupby *

df.set_index(['c', 'd']).groupby('a').apply(lambda df: df.index.tolist()).to_dict() 
 
{8: [(17, 1.0), (19, 1.0), (13, 0.0)], 9: [(8, 5.0)]}