I have an numpy ndarray with shape (2,3,3),for example:
array([[[ 1, 2, 3],
[ 4, 5, 6],
[12, 34, 90]],
[[ 4, 5, 6],
[ 2, 5, 6],
[ 7, 3, 4]]])
I am getting lost in np.sum(above ndarray ,axis=1), why that answer is:
array([[17, 41, 99],
[13, 13, 16]])
Thanks
Axis 1 is the direction along the columns In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns.
Numpy arrays are mutable objects that have clearly defined in place operations. If a and b are arrays of the same shape, a += b adds the two arrays together, using a as an output buffer.
Essentially, the NumPy sum function sums up the elements of an array. It just takes the elements within a NumPy array (an ndarray object) and adds them together. Having said that, it can get a little more complicated. It's possible to also add up the rows or add up the columns of an array.
Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1).
Let A be the array, then in your example when the axis is 1, [i,:,k] is added. Likewise, for axis 0, [:,j,k] are added and when axis is 2, [i,j,:] are added.
A = np.array([
[[ 1, 2, 3],[ 4, 5, 6], [12, 34, 90]],
[[ 4, 5, 6],[ 2, 5, 6], [ 7, 3, 4]]
])
np.sum(A,axis = 0)
array([[ 5, 7, 9],
[ 6, 10, 12],
[19, 37, 94]])
np.sum(A,axis = 1)
array([[17, 41, 99],
[13, 13, 16]])
np.sum(A,axis = 2)
array([[ 6, 15,136],
[15, 13, 14]])
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