Extract array from arrays of arrays

I have arrays like this:

arr = np.array([[[ -1.,  -1.,  -1.,  0.,   0.,   0.],
                [ 0.1,  0.1,  0.1,  2.,   3.,   4.]], # <-- this one

               [[ -1.,  -1.,  -1.,  0.,   0.,  -1.],
                [ 0.1,  0.1,  0.1, 16.,  17.,  0.1]], # <-- and this one

               [[ -1.,  -1.,  -1.,  0.,   0.,   0.],
                [ 0.1,  0.1,  0.1,  4.,   5.,   6.]], # <-- and this one

               [[  0.,   0.,   0., -1.,   0.,   0.],
                [  1.,   2.,   3., 0.1,   1.,   2.]], # <-- and this one

               [[ -1.,  -1.,   0.,  0.,   0.,   0.],
                [ 0.1,  0.1,   1.,  9.,  10.,  11.]]]) # <-- and the last one

      

I want to extract the 2nd array in each array and the result should be as follows:

res = [[ 0.1,  0.1,  0.1,  2.,   3.,   4.],
       [ 0.1,  0.1,  0.1, 16.,  17.,  0.1],
       [ 0.1,  0.1,  0.1,  4.,   5.,   6.],
       [  1.,   2.,   3., 0.1,   1.,   2.],
       [ 0.1,  0.1,   1.,  9.,  10.,  11.]]

      

I want to get res

in one line of code, I tried this but it didn't work

arr[:][1] # select the element 1 in each array
# I got
array([[ -1. ,  -1. ,  -1. ,   0. ,   0. ,  -1. ],
       [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1]])

      

Can someone explain why?

The only solution I found was to explicitly list every index ( arr[0][1]...

) that I didn't like.

+3


source to share


2 answers


It is an array 3D

and you are trying to select the second element of the second axis and retrieve all elements along the other axes. So, this is as simple as -

arr[:,1,:]

      

We can omit the enum :

for the rear axles, so it simplifies to -



arr[:,1]

      

Example run -

In [360]: arr
Out[360]: 
array([[[ -1. ,  -1. ,  -1. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   0.1,   2. ,   3. ,   4. ]],

       [[ -1. ,  -1. ,  -1. ,   0. ,   0. ,  -1. ],
        [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1]],

       [[ -1. ,  -1. ,  -1. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   0.1,   4. ,   5. ,   6. ]],

       [[  0. ,   0. ,   0. ,  -1. ,   0. ,   0. ],
        [  1. ,   2. ,   3. ,   0.1,   1. ,   2. ]],

       [[ -1. ,  -1. ,   0. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   1. ,   9. ,  10. ,  11. ]]])

In [361]: arr[:,1]
Out[361]: 
array([[  0.1,   0.1,   0.1,   2. ,   3. ,   4. ],
       [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1],
       [  0.1,   0.1,   0.1,   4. ,   5. ,   6. ],
       [  1. ,   2. ,   3. ,   0.1,   1. ,   2. ],
       [  0.1,   0.1,   1. ,   9. ,  10. ,  11. ]])

      

+5


source


I don't know anything about numpy, so there might be an easier way to do this. But a simple list comprehension will work:



[a[1] for a in arr]

      

+2


source







All Articles