Home > Net >  Indexing numpy array with an array of indices
Indexing numpy array with an array of indices

Time:11-05

I have 2 numpy arrays: X with shape (..., 12, 3) and Y with shape (..., 12), where the ... is the same in both cases. I get an array of indices using:

idx = np.argmin(Y, axis=-1)

which afterwards I want to use to get the corresponding elements from array X and Y. However, I run into issues due to the extra dimensions. For Y, I can do e.g.

Y[np.arange(Y.shape[0]), idx]

however this requires me to know the shape of ... which will not be the case at all times. How do I do this in a better way?

CodePudding user response:

Okay, since I figured it out, here is the way to do it:

idx = np.argmin(Y, axis=-1)
indices = np.indices(idx.shape)
min_from_X = X[indices[0], ..., idx, :]
min_from_Y = Y[indices[0], ..., idx]

CodePudding user response:

class args: {
    . . . = str[]
}
# Inside the arrays you should have put this variable for the arguments;
x = [. . ., 12, 3]
y = [. . ., 12]
class args: {
    . . . = str[]
}
# Remove the argument if the item is in the args class,
# simply meaning to remove the args... 
if args[. . .] in x: {
    pop(x[1])
}
if args[. . .] in y: {
    pop(y[1])
}
  • Related