问题描述
我想获取numpy数组元素的第一个索引,该索引大于同一数组的某些特定元素.我尝试了以下操作:
I want to get first index of numpy array element which is greater than some specific element of that same array. I tried following:
>>> Q5=[[1,2,3],[4,5,6]]
>>> Q5 = np.array(Q5)
>>> Q5[0][Q5>Q5[0,0]]
array([2, 3])
>>> np.where(Q5[0]>Q5[0,0])
(array([1, 2], dtype=int32),)
>>> np.where(Q5[0]>Q5[0,0])[0][0]
1
Q1.以上是获取大于 Q5 [0,0]
的 Q5 [0]
中元素的第一索引的正确方法?
Q1. Is above correct way to obtain first index of an element in Q5[0]
greater than Q5[0,0]
?
我更关心 np.where(Q5 [0]> Q5 [0,0])
返回元组(array([1,2],dtype = int32),)
,因此要求我在 np.where(Q5 [0]> Q5 [0,0])的末尾对
. [0] [0]
进行双索引[0] [0]
I am more concerned with np.where(Q5[0]>Q5[0,0])
returning tuple (array([1, 2], dtype=int32),)
and hence requiring me to double index [0][0]
at the end of np.where(Q5[0]>Q5[0,0])[0][0]
.
第二季度.为什么返回元组,但下面返回正确的numpy数组?
Q2. Why this return tuple, but below returns proper numpy array?
>>> np.where(Q5[0]>Q5[0,0],Q5[0],-1)
array([-1, 2, 3])
这样我就可以直接建立索引:
So that I can index directly:
>>> np.where(Q5[0]>Q5[0,0],Q5[0],-1)[1]
2
推荐答案
将 argmax
与布尔数组一起使用将为您提供第一个True的索引.
Using argmax
with a boolean array will give you the index of the first True.
In [54]: q
Out[54]:
array([[1, 2, 3],
[4, 5, 6]])
In [55]: q > q[0,0]
Out[55]:
array([[False, True, True],
[ True, True, True]], dtype=bool)
argmax
可以采用轴/尺寸参数.
argmax
can take an axis/dimension argument.
In [56]: np.argmax(q > q[0,0], 0)
Out[56]: array([1, 0, 0], dtype=int64)
这表示第一个True为第0列的索引为1,为第1列和第2列的索引为零.
That says the first True is index one for column zero and index zero for columns one and two.
In [57]: np.argmax(q > q[0,0], 1)
Out[57]: array([1, 0], dtype=int64)
这表示第一个True是第1行的索引1和第1行的索引0.
That says the first True is index one for row zero and index zero for row one.
不,我将 argmax
与 1
用作 axis
参数,然后从该结果中选择第一项.
No I would use argmax
with 1
for the axis
argument then select the first item from that result.
您告诉它返回False值的 -1
,返回True值的 Q5 [0]
项.
You told it to return -1
for False values and return Q5[0]
items for True values.
您很幸运,并选择了正确的索引.
You got lucky and chose the correct index.
这篇关于了解numpy.where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!