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

Forming an array with elements in specific positions from multiple arrays in Python

I have an array A. I want to take the first, second,…,ninth elements of each A[0],A[1],A[2] to form a new array B. I present the current and expected outputs.

import numpy as np

A=np.array([np.array([[1, 2, 3],
              [4, 5, 6 ],
              [7, 8, 9]]),
       np.array([[[10, 11, 12],
               [13, 14, 15 ],
               [16, 17, 18]]]),
       np.array([[[19, 20, 21],
               [22, 23, 24],
               [25, 26, 27]]])], dtype=object)

for t in range(0,len(A)):
    B=A[0][t][0]
    print([B])

The current output is

[1]
[4]
[7]

The expected output is

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

array([[1,10,19],
        [2,11,20],
        [3,12,21],
        [4,13,22],
        [5,14,23],
        [6,15,24],
        [7,16,25],
        [8,17,26],
        [9,18,27]])

>Solution :

You can traverse the array, append all values as columns and transpose the resulting matrix:

import numpy as np

A=np.array([np.array([[1, 2, 3],
              [4, 5, 6 ],
              [7, 8, 9]]),
       np.array([[[10, 11, 12],
               [13, 14, 15 ],
               [16, 17, 18]]]),
       np.array([[[19, 20, 21],
               [22, 23, 24],
               [25, 26, 27]]])], dtype=object)
               
out = np.array([A[i].flatten() for i in range(len(A))]).transpose()
#out = np.array([i.flatten() for i in A]).transpose() #Second option
print(out)

Output:

[[ 1 10 19]
 [ 2 11 20]
 [ 3 12 21]
 [ 4 13 22]
 [ 5 14 23]
 [ 6 15 24]
 [ 7 16 25]
 [ 8 17 26]
 [ 9 18 27]]
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