对 NumPy 数组中连续值的切片求和

Sum slices of consecutive values in a NumPy array(对 NumPy 数组中连续值的切片求和)
本文介绍了对 NumPy 数组中连续值的切片求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设我有一个包含 10 个值的 numpy 数组 a.这里只是一个示例情况,尽管我想对长度为 100 的数组重复相同的操作.

Let's say I have a numpy array a containing 10 values. Just an example situation here, although I would like to repeat the same for an array with length 100.

a = np.array([1,2,3,4,5,6,7,8,9,10])

我想将前 5 个值与后 5 个值相加,以此类推,并将它们存储在一个新的空列表中,例如 b.

I would like to sum the first 5 values followed by the second 5 values and so on and store them in a new empty list say b.

所以 b 将包含 b = [15,40].

我该怎么做呢?

推荐答案

试试这个列表推导:

b = [sum(a[current: current+5]) for current in xrange(0, len(a), 5)]

它一次从列表中取出 5 个切片,将它们相加并构造一个列表.也适用于长度不是 5 的倍数的列表.

It takes slices of 5 at a time from the list, sums them up and constructs a list. Also works for lists which aren't a multiple of 5 in length.

(xrange在python3+中应该是range)

(xrange should be range in python3+)

这篇关于对 NumPy 数组中连续值的切片求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)