首页 > 解决方案 > 如何从 pandas Dataframe groupby 对象中获取一系列 json/字典

问题描述

我有一个超过 2 列(Col1、Col2 等)的数据框,我想生成一个索引为 Col1 的系列,并且系列的值是字典,其中键是 Col2,值(的dict) 是元组 (Col1, Col2) 的出现次数。

假设数据框是这样的:

    Col1 Col2 Col3 ...
 0    A    b   ... 
 1    B    e   ... 
 2    A    a   ... 
 3    C    a   ... 
 4    A    b   ... 
 5    B    c   ... 
 6    A    e   ... 
 7    B    c   ... 

我想要的输出是:

A {'a':1,'b':2,'e':1}
B {'c':2,'e':1}
C {'a':1}

我通过这个循环设法做到了:

for t in my_df['Col1'].unique(): 
  my_series.loc[t] = my_df[my_df['Col1'] == t].groupby('Col2').size().to_json()

但我想知道是否有一种方法可以使用 pandas 方法更有效地做到这一点,而无需迭代。

我还尝试使用两个索引进行 groupby:

   my_df.groupby(['Col1','Col2']).size() 
   >
   Col1  Col2
    A     a     1
          b     2
          e     1
    B     c     2
          e     1
    C     a     1

但找不到下一步将结果转换为 dict 的系列,如上图所示

标签: pythonjsonpandas-groupby

解决方案


你需要一个 defaultdict:

import collections

resul = collections.defaultdict(dict)
for row in my_df.groupby(['Col1','Col2']).size().iteritems():
    resul[row[0][0]][row[0][1]] = row[1]

pprint.pprint(resul)

按预期给出:

defaultdict(<class 'dict'>,
            {'A': {'a': 1, 'b': 2, 'e': 1},
             'B': {'c': 2, 'e': 1},
             'C': {'a': 1}})

如果你想摆脱 defaultdict 而想要一个普通的 dict:

resul = dict(resul)

推荐阅读