简体   繁体   English

计算python / pandas中组的平均值

[英]Calculating the mean of groups in python/pandas

My grouped data looks like: 我的分组数据如下:

deviceid                                  time    
01691cbb94f16f737e4c83eca8e5f5e5390c2801  January       10
022009f075929be71975ce70db19cd47780b112f  April        566
                                          August       210
                                          January        4
                                          July         578
                                          June        1048
                                          May         1483
02bad1cdf92fbaa9327a65babc1c081e59fbf435  November     309
                                          October       54

Where the last column represents the count. 最后一列代表计数的位置。 I obtained this grouped representation using the expression: 我使用表达式获得了这个分组表示:

data1.groupby(['deviceid', 'time'])

How do I get the average for each device id, ie, the sum of the counts of all months divided by the number of months? 如何获得每个设备ID的平均值,即所有月份的计数总和除以月数? My output should look like: 我的输出应该如下:

deviceid                                  mean    
01691cbb94f16f737e4c83eca8e5f5e5390c2801  10
022009f075929be71975ce70db19cd47780b112f  777.8
02bad1cdf92fbaa9327a65babc1c081e59fbf435  181.5

You an specify the level in the mean method: 您可以在mean方法中指定级别:

s.mean(level=0)  # or: s.mean(level='deviceid')

This is equivalent to grouping by the first level of the index and taking the mean of each group: s.groupby(level=0).mean() 这相当于按索引的第一级分组并取每组的平均值: s.groupby(level=0).mean()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM