Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a multidimensional numpy array into one array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading