繁体   English   中英

如何在 Python 中合并列表值的总和?

[英]How to bin the sum of list values in Python?

我需要一些帮助来分箱我的数据值。 需要一个类似直方图的函数,但我不想列出出现的次数,只是每个 bin 的值的总和。

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

箱的数量以及持续时间最终可以改变。 例如,它还需要工作 31 天和 5 个垃圾箱。

有谁知道如何有效地做到这一点? 是否有可用的 Python 函数可以做到这一点? 否则,for 循环的实现能够将列表中的 n 个值相加,直到持续时间结束。

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

    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)]

另一种方法是通过重塑和求和。 我知道你已经有了一个有效的答案,但你需要大量练习 numpy 列表操作

import numpy

# this works when the list divides exactly into bins
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]
duration = len(followersList)
bins = 10
binWidth = round(duration / bins)
print(numpy.array(followersList).reshape(bins, binWidth).sum(axis=1))

# otherwhise we have to pad with zero till its a multiple of containers
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, 1]
binWidth = 3
bins = (len(followersList) - 1) // binWidth + 1  # ceiling division
print(
    numpy.pad(followersList, (0, bins * binWidth - len(followersList)), 'constant').reshape(bins, binWidth).sum(axis=1))

我遇到了同样的问题。 我认为应该有numpyscipy提供的一些功能来做到这一点,但我找不到。 我最接近的是这个:

bins = 10
sum_of_bins = [np.sum(arr) for arr in np.array_split(followersList, bins)]

它使用函数np.array_split将大数组拆分为要应用求和的较小数组。 你也可以使用np.split ,但如果followerlist不能被bins完全划分,后者会抛出错误。

暂无
暂无

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

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