【发布时间】:2017-12-03 01:17:20
【问题描述】:
我有一个如下的数据框:
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
如果我按两列分组并计算大小,
df.groupby(['regiment','company']).size()
我得到以下信息:
regiment company
Dragoons 1st 2
2nd 2
Nighthawks 1st 2
2nd 2
Scouts 1st 2
2nd 2
dtype: int64
我想要的输出是一个字典,如下所示:
{'Dragoons':{'1st':2,'2nd':2},
'Nighthawks': {'1st':2,'2nd':2},
... }
我尝试了不同的方法,但无济于事。有没有相对干净的方法来实现上述目标?
非常感谢您!!!!
【问题讨论】:
标签: python pandas dictionary multi-index