计算python数组中每5个元素的总和 [英] Calculate the sum of every 5 elements in a python array

查看:568
本文介绍了计算python数组中每5个元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python数组,我想在其中计算每5个元素的总和.就我而言,我的数组c具有十个元素. (实际上,它还有很多元素.)

I have a python array in which I want to calculate the sum of every 5 elements. In my case I have the array c with ten elements. (In reality it has a lot more elements.)

c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]

所以最后我想有一个新的数组(c_new),它应该显示前5个元素和后5个元素的总和

So finally I would like to have a new array (c_new) which should show the sum of the first 5 elements, and the second 5 elements

所以结果应该是一个

1+0+0+0+0 = 1
2+0+0+0+0 = 2

c_new = [1, 2]

谢谢您的帮助 马库斯

Thank you for your help Markus

推荐答案

您可以通过在要拆分和求和的地方传递索引来使用np.add.reduceat:

You can use np.add.reduceat by passing indices where you want to split and sum:

import numpy as np
c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]
np.add.reduceat(c, np.arange(0, len(c), 5))
# array([1, 2])

这篇关于计算python数组中每5个元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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