Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to iterate over multiple ranges to create a multidimensional ndarray from another

I have:

>>> import numpy as np
>>> a = np.arange(25).reshape(5, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

How do I get an array which is the sum of a number and the number below it:

array([[7,  9,  11,],   # 1+6=7 , 2+7=9 , 3+8=11
       [17, 19, 21,],
       [27, 29, 31,]])

I'd like to do this by iterating over the original array. Something like:

b[x,y] = [a[x,y]+a[x+1,y] for x in range(0,3) for y in range(1,4)] #ERROR!

although this doesn't work for syntax reasons. Can someone please give me the proper syntax? I'm not a professional programmer, and am new to Python. Thank you in advance.

like image 946
user2974839 Avatar asked Jan 29 '26 11:01

user2974839


1 Answers

Use slices to pick out (1) all but the last row of the array and (2) all but the first row of the array. Then add them.

>>> a[:-1,:] + a[1:,:]
array([[ 5,  7,  9, 11, 13],
       [15, 17, 19, 21, 23],
       [25, 27, 29, 31, 33],
       [35, 37, 39, 41, 43]])
like image 142
Vebjorn Ljosa Avatar answered Feb 01 '26 02:02

Vebjorn Ljosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!