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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With