gpt4 book ai didi

python - Pandas 按索引分组并计算总和

转载 作者:太空宇宙 更新时间:2023-11-03 14:03:36 25 4
gpt4 key购买 nike

我有以下系列:

s = pd.Series({
(0, 'InData'): 2944.51697, (0, 'InInterests'): 3703.208935,
(1, 'InData'): 6207.58004, (1, 'InInterests'): 3505.068411,
(2, 'InData'): 8133.00273, (2, 'InInterests'): 3735.028306,
(3, 'InData'): 9426.70471, (3, 'InInterests'): 2665.989291,
(4, 'InData'): 2604.1578, (4, 'InInterests'): 3103.310729,
(5, 'InData'): 6784.82916, (5, 'InInterests'): 3293.815375,
(6, 'InData'): 6823.6174, (6, 'InInterests'): 4121.83398,
(7, 'InData'): 4072.70277, (7, 'InInterests'): 3033.609368,
(8, 'InData'): 4614.60824, (8, 'InInterests'): 2955.216811,
(9, 'InData'): 6986.50075, (9, 'InInterests'): 2986.820394
}, name='KilobytesRaw').rename_axis(index=['Node', 'Type'])

:

Node  Type       
0 InData 2944.516970
InInterests 3703.208935
1 InData 6207.580040
InInterests 3505.068411
2 InData 8133.002730
InInterests 3735.028306
3 InData 9426.704710
InInterests 2665.989291
4 InData 2604.157800
InInterests 3103.310729
5 InData 6784.829160
InInterests 3293.815375
6 InData 6823.617400
InInterests 4121.833980
7 InData 4072.702770
InInterests 3033.609368
8 InData 4614.608240
InInterests 2955.216811
9 InData 6986.500750
InInterests 2986.820394
Name: KilobytesRaw, dtype: float64

我想计算 InDataInInterests 的总和,但在 Pandas 中找不到这种情况 indexing page ,也不在 Google 上。

所以我希望我的结果看起来像这样:

Node
0 6647.725905
1 9712.648451
...
9 9973.321144

最佳答案

Groupby sum支持传递级别编号而不是列名称。这允许在一个级别而不是一个列上进行求和:

s.groupby(level=0).sum()

既然索引级别是命名的,我们也可以使用索引名称代替级别编号:

s.groupby(level='Node').sum()

任一选项都会产生:

Node
0 6647.725905
1 9712.648451
2 11868.031036
3 12092.694001
4 5707.468529
5 10078.644535
6 10945.451380
7 7106.312138
8 7569.825051
9 9973.321144
Name: KilobytesRaw, dtype: float64

关于python - Pandas 按索引分组并计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com