从numpy.argmax结果中提取numpy数组切片

时间:2013-01-08 18:58:25

标签: python numpy

我有一个(3,3)numpy数组,想要找出绝对元素的符号 值是最大值:

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

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

给出了我需要的元素的索引s = [ 0,1,1]

如何使用此数组提取元素[ -2.1, -6.1, 5]以找出其符号?

2 个答案:

答案 0 :(得分:6)

试试这个:

# 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])]

答案 1 :(得分:0)

部分答案:使用signsignbit

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)