I have a multidimensional numpy array that has the shape (5, 6192, 1) so essentially 5 arrays of length 6192 into one array.
How could I add the elements of all the arrays into one array of length 6192 in the following way. For example if the 5 arrays look like
ar1 = [1,2,3...]
ar2 = [1,2,3...]
ar3 = [1,2,3...]
ar4 = [1,2,3...]
ar5 = [1,2,3...]
I want my final array to look like:
ar = [5,10,15,...]
So for each inner array, add the values of each same position into a new value for the final array that is the sum of all the values in this position.
The shape should be, I guess shape(1,6192,1).
CodePudding user response:
IIUC, simply use numpy.sum
:
ar1 = [1,2,3]
ar2 = [1,2,3]
ar3 = [1,2,3]
ar4 = [1,2,3]
ar5 = [1,2,3]
arrays = [ar1, ar2, ar3, ar4, ar5]
ar = np.sum(arrays, axis=0)
output: array([ 5, 10, 15])
If really the shapes you describe are correct:
arr = np.array(arrays).reshape((5, 3, 1))
print(arr.shape)
# (5, 3, 1)
ar = np.sum(arr, axis=0)[None,:]
print(ar.shape)
# (1, 3, 1)