Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

python - Sum slices of consecutive values in a NumPy array

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

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.

So b would contain b = [15,40].

How do I go about doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way is to use the add ufunc with its reduceat method:

>>> np.add.reduceat(a, [0,5])
array([15, 40])

This sums the slices a[0:5] and a[5:] and returns a new array.

If you want a Python list, you could call tolist() on the returned array.

You can use any list of indexes with the method (and they do not have to evenly spaced). For example, if you want slices of 5 each time on an array of length 100:

>>> b = np.arange(100)
>>> np.add.reduceat(b, range(0, 100, 5))
array([ 10,  35,  60,  85, 110, 135, 160, 185, 210, 235, 260, 285, 310,
   335, 360, 385, 410, 435, 460, 485])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...