GeoMonkey
GeoMonkey

Reputation: 1671

Subset one numpy array by another

At a basic level I can index one numpy array by another so I can return the index of an array, such that:

a = [1,2,3,4,5,6]

b = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

and the index of 0.6 can be found by:

c = a[b==0.6]

However, now I have 3D arrays and I'm unable to get my head around what I need.

I have 3 arrays:

A = [[21,22,23....48,49,50]] # An index over the range 20-50 with shape (1,30)

B = [[0.1,0.6,0.5,0.4,0.8...0.7,0.2,0.4],
     ..................................
     [0.5,0.2,0.7,0.1,0.5...0.8,0.9,0.3]] # This is my data with shape (40000, 30)

C = [[0.8],........[0.9]] # Maximum values from each array in B with shape (40000,1)

I would like to know the position (from A) by indexing the max value (C) in each of the arrays in my data (B)

I have tried:

D = A[B==C]

but I keep getting an error:

IndexError: index 1 is out of bounds for axis 0 with size 1

On its own I can get:

B==C # prints as arrays of True or False

but I can't retrieve the index position from A.

Any help is appreciated!

Upvotes: 1

Views: 145

Answers (1)

Garrett R
Garrett R

Reputation: 2662

Is this kind of what you are a looking for? Getting the index where the max value is at each row using the argmax function and the use the indices to get the corresponding value in A.

In [16]: x = np.random.random((20, 30))
In [16]: max_inds = x.argmax(axis=1)

In [17]: max_inds.shape
Out[17]: (20,)

In [18]: A = np.arange(x.shape[1])

In [19]: A.shape
Out[19]: (30,)

In [20]: A[max_inds]
Out[20]: 
array([20,  5, 27, 19, 27, 21, 18, 25, 10, 24, 16, 21,  6,  7, 27, 17, 24,
        8, 27,  8])

Upvotes: 1

Related Questions