如何在Python中对列表值的总和进行装箱? [英] How to bin the sum of list values in Python?

查看:66
本文介绍了如何在Python中对列表值的总和进行装箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对数据值进行装箱时,我需要一些帮助.需要一个类似于直方图的函数,但我不想列出每个事件的发生次数,而只是列出每个bin的值之和.

I need some help in binning my data values. Need a histogram-like function, but I don't want to list the occurrences, just the sum of the values for each bin.

在下面的示例中,我有一个列表,其中包含30天的Twitter关注者数量.假设我要10个垃圾箱,那么每个垃圾箱将采用30/10 = 3天的值.在前三天中,对于bin 2 12618等,bin 1的值将为1391 + 142 + 0 = 1533,直到bin 10.

In my example below I have a list with the number of Twitter followers for 30 days. Lets say I want 10 bins, then each bin would take the values of 30 / 10 = 3 days. For the first three days the value for bin 1 would be 1391 + 142 + 0 = 1533 for bin 2 12618, etc., up to bin 10.

箱的数量和持续时间最终可能会有所不同.例如,它还需要工作31天和5个垃圾箱.

The number of bins as well as the duration could eventually be varied. It also needs to work for a duration of 31 days and 5 bins, for instance.

任何人都知道如何有效地做到这一点吗?有可用的Python函数可以做到这一点吗?否则,将实现for循环,该循环能够将列表中的n个值加在一起,直到持续时间结束.

Anyone knows how to do this efficiently? Is there a Python function available that could do this? Otherwise an implementation of a for loop that is able to sum n number of values in a list together until end of duration.

所有帮助将不胜感激:)谢谢!

All help would be highly appreciated :) Thanks!

    followersList = [1391, 142, 0, 0, 12618, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 456, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    duration = 30
    bins = 10
    binWidth = round(duration / bins)

    #
    # for loop or python function that sums values for each bin
    #

推荐答案

您可以这样做:

bin_width = int(round(duration / bins))
followers = [sum(followersList[i:i+bin_width]) for i in xrange(0, duration, bin_width)]

这篇关于如何在Python中对列表值的总和进行装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆