分组索引的嵌套字典

时间:2018-09-26 17:11:22

标签: python pandas

>>> df = pd.DataFrame({'a': [1,1,1,2,2,3,3,3,3,4,4,5,5], 
'b': [0,1,1,0,1,0,0,1,4,1,0,3,0], 
'v': [2,4,3,7,6,5,9,3,2,4,5,2,3]})
>>> df
    a  b  v
0   1  0  2
1   1  1  4
2   1  1  3
3   2  0  7
4   2  1  6
5   3  0  5
6   3  0  9
7   3  1  3
8   3  4  2
9   4  1  4
10  4  0  5
11  5  3  2
12  5  0  3
>>> df.groupby(by =['a', 'b']).groups
{(2, 0): [3], (5, 0): [12], (3, 0): [5, 6], (5, 1): [11], (1, 0): [0], (3, 
1): [7, 8], (4, 1): [9], (1, 1): [1, 2], (2, 1): [4], (4, 0): [10]}

要获取嵌套的索引字典,我正在做

>>> df['idx'] = df.index
>>> {k: {kk: vv for kk, vv in v.items() if vv is not None} for k, v in 
df.groupby(by =['a','b']).idx.apply(list).unstack().to_dict('index').items()}
{1: {0: [0], 1: [1, 2]}, 2: {0: [3], 1: [4]}, 3: {0: [5, 6], 1: [7, 8]}, 4: 
{0: [10], 1: [9]}, 5: {0: [12], 1: [11]}}

这是通过改编@piRSquared的答案here。 是否有更直接的方法来获得此结果?

1 个答案:

答案 0 :(得分:2)

使用两个groupby,我不确定遵循解决方案的效率

df.reset_index().groupby('a').apply(lambda x : x.groupby('b')['index'].apply(list).to_dict()).to_dict()
Out[271]: 
{1: {0: [0], 1: [1, 2]},
 2: {0: [3], 1: [4]},
 3: {0: [5, 6], 1: [7], 4: [8]},
 4: {0: [10], 1: [9]},
 5: {0: [12], 3: [11]}}