Python:在groupby对象中获取最大索引?
这是我的Python:在groupby对象中获取最大索引?,python,pandas,Python,Pandas,这是我的groupby聚合后的结果: Message Month Hour 1 0 192 1 152 2 64 3 117 4 59 5 15 6 73 7 53 8 33
groupby
聚合后的结果:
Message
Month Hour
1 0 192
1 152
2 64
3 117
4 59
5 15
6 73
7 53
8 33
9 116
10 219
11 264
12 686
13 878
14 320
15 287
16 447
17 792
18 886
19 861
20 458
21 375
22 434
23 238
2 0 49
1 25
2 23
3 15
6 45
7 23
.
.
.
我想获取小时数
,该小时数在月份
中有最多的消息
例如,在一月份,我想得到msg计数最高的18
如何在代码中实现它?使用,但它返回元组,因为多索引
,所以需要str[1]
来选择第二个值:
s = df.groupby(level=0)['Message'].idxmax().str[1]
print (s)
Month
1 18
2 0
Name: Message, dtype: int64
详细信息:
print (df.groupby(level=0)['Message'].idxmax())
Month
1 (1, 18)
2 (2, 0)
Name: Message, dtype: object
另一种解决方案是通过以下方法按多索引的第一级创建列:
print (df.reset_index(level=0).groupby('Month')['Message'].idxmax())
Month
1 18
2 0
Name: Message, dtype: int64