billv1179
billv1179

Reputation: 323

Iterate through multidimensional numpy array and select values from a 1D array

I have a one dimensional numpy array of shape (99,) which appears like the following:

[1 1 0 2 0 1 2 0 1 2 1 2 0 1 0 0 1 0 0 1 0 2 1 1 2 1 0 1 2 0 0 0 0 0 0 1 2
  1 1 0 1 1 2 1 1 0 1 0 1 2 0 0 2 0 1 1 2 0 2 0 2 0 2 0 0 2 1 0 0 0 1 0 2 1
1 0 0 1 1 1 0 1 1 1 2 2 0 0 2 0 1 1 1 2 2 2 0 2 1]

I would like to use the above array to select values from a multidimensional array of shape (99,3). Here are the first 5 rows of this array:

 array([[ 257.985,  332.58 , 2524.92 ],
   [ 254.29 ,  330.785, 2494.01 ],
   [ 253.81 ,  335.74 , 2499.5  ],
   [ 255.16 ,  336.7  , 2479.9  ],
   [ 249.98 ,  329.48 , 2451.32 ]])

I requesting coding help with this part. I'm looking to use the first array as an index to select values from the second multidim array shown above, creating a new array from this. For example, the first 5 values of this new array would be:

[332.58, 330.785, 253.81, 2479.9, 249.98, ...]

Upvotes: 1

Views: 146

Answers (2)

Liam Spring
Liam Spring

Reputation: 59

This is another way you can do this (it's more beginner-friendly):

import numpy as np

a = np.array([1, 1, 0, 2 ,0])

b =  np.array([[ 257.985,  332.58 , 2524.92 ],
   [ 254.29 ,  330.785, 2494.01 ],
   [ 253.81 ,  335.74 , 2499.5  ],
   [ 255.16 ,  336.7  , 2479.9  ],
   [ 249.98 ,  329.48 , 2451.32 ]])

c=[]
p = 0
for i in a:
    if i == 0:
        c.append(b[p][0])
    elif i == 1:
        c.append(b[p][1])
    else:
        c.append(b[p][2])
    p+=1

print(c)

Upvotes: 1

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

With "fancy" indexing:

multi_dim_arr[np.arange(len(multi_dim_arr)), one_dim_arr]

where multi_dim_arr is 99x3 matrix and one_dim_arr is 99-vector.

First set of indices goes from 0..98 others are your {0, 1, 2} indices from the 1D array. NumPy then selects pair-wise.

Upvotes: 1

Related Questions