Using numpy.argmax() on multidimensional arrays
Asked Answered
I

2

14

I have a 4 dimensional array, i.e., data.shape = (20,30,33,288). I am finding the index of the closest array to n using

index = abs(data - n).argmin(axis = 1), so
index.shape = (20,33,288) with the indices varying. 

I would like to use data[index] = "values" with values.shape = (20,33,288), but data[index] returns the error "index (8) out of range (0<=index<1) in dimension 0" or this operation takes a relatively long time to compute and returns a matrix with a shape that doesn't seem to make sense.

How do I return a array of correct values? i.e.,

data[index] = "values" with values.shape = (20,33,288)

This seems like a simple problem, is there a simple answer?

I would eventually like to find index2 = abs(data - n2).argmin(axis = 1), so I can perform an operation, say sum data at index to data at index2 without looping through the variables. Is this possible?

I am using python2.7 and numpy version 1.5.1.

Insupportable answered 27/4, 2011 at 1:31 Comment(0)
C
15

You should be able to access the maximum values indexed by index using numpy.indices():

x, z, t = numpy.indices(index.shape)
data[x, index, z, t]
Constance answered 27/4, 2011 at 10:5 Comment(2)
Is there also an answer when one doesn't know the ndim?Gilkey
@AndreasMueller: Yes, use tup[:axis] + (index,) + tup[axis:] as index for data, where tup is the tuple returned by numpy.indices().Constance
W
1

If I understood you correctly, this should work:

numpy.put(data, index, values)

I learned something new today, thanks.

Wattage answered 27/4, 2011 at 3:24 Comment(1)
Thanks for the response. I don't have "values," so I do not think I can use numpy.put. I believe Sven's answer will work.Insupportable

© 2022 - 2024 — McMap. All rights reserved.