arun
arun

Reputation: 1380

Extracting numpy array slice from numpy.argmax results

I have a (3,3) numpy array and would like to figure out the sign of the element whose absolute value is maximum:

X = [[-2.1,  2,  3],
     [ 1, -6.1,  5],
     [ 0,  1,  1]]

s = numpy.argmax(numpy.abs(X),axis=0) 

gives me the indices of the elements that I need, s = [ 0,1,1].

How can I use this array to extract the elements [ -2.1, -6.1, 5] to figure out their sign?

Upvotes: 4

Views: 2054

Answers (2)

Steve Tjoa
Steve Tjoa

Reputation: 61064

Partial answer: Usesign or signbit.

In [8]: x = numpy.array([-2.1, -6.1, 5])

In [9]: numpy.sign(x)
Out[9]: array([-1., -1.,  1.])

In [10]: numpy.signbit(x)
Out[10]: array([ True,  True, False], dtype=bool)

Upvotes: 0

Bi Rico
Bi Rico

Reputation: 25823

Try this:

# You might need to do this to get X as an ndarray (for example if X is a list)
X = numpy.asarray(X)

# Then you can simply do
X[s, [0, 1, 2]]

# Or more generally
X_argmax = X[s, numpy.arange(X.shape[1])]

Upvotes: 7

Related Questions