Python 从哪里到哪里?
在where格式的输出中是否有快速获取argwhere输出的方法 让我用一些代码向您展示我正在做什么:Python 从哪里到哪里?,python,numpy,Python,Numpy,在where格式的输出中是否有快速获取argwhere输出的方法 让我用一些代码向您展示我正在做什么: In [123]: filter = np.where(scores[:,:,:,4,:] > 21000) In [124]: filter Out[124]: (array([ 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 23, 23, 23, 23, 23]), array([13, 13, 4, 4, 4, 4, 4,
In [123]: filter = np.where(scores[:,:,:,4,:] > 21000)
In [124]: filter
Out[124]:
(array([ 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 23, 23, 23, 23, 23]),
array([13, 13, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5]),
array([0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2]),
array([44, 44, 0, 1, 2, 3, 6, 8, 12, 14, 22, 31, 58, 76, 82, 41]))
In [125]: filter2 = np.argwhere(scores[:,:,:,4,:] > 21000)
In [126]: filter2
Out[126]:
array([[ 2, 13, 0, 44],
[ 2, 13, 1, 44],
[ 4, 4, 3, 0],
[ 4, 4, 3, 1],
[ 4, 4, 3, 2],
[ 4, 4, 3, 3],
[ 4, 4, 3, 6],
[ 4, 4, 3, 8],
[ 4, 4, 3, 12],
[ 4, 4, 3, 14],
[ 4, 4, 3, 22],
[23, 4, 2, 31],
[23, 4, 2, 58],
[23, 4, 2, 76],
[23, 4, 2, 82],
[23, 5, 2, 41]])
In [150]: scores[:,:,:,4,:][filter]
Out[150]:
array([ 21344., 21344., 24672., 24672., 24672., 24672., 25232.,
25232., 25232., 25232., 24672., 21152., 21152., 21152.,
21152., 21344.], dtype=float16)
In [129]: filter2[np.argsort(scores[:,:,:,4,:][filter])]
Out[129]:
array([[23, 4, 2, 31],
[23, 4, 2, 58],
[23, 4, 2, 76],
[23, 4, 2, 82],
[ 2, 13, 0, 44],
[ 2, 13, 1, 44],
[23, 5, 2, 41],
[ 4, 4, 3, 0],
[ 4, 4, 3, 1],
[ 4, 4, 3, 2],
[ 4, 4, 3, 3],
[ 4, 4, 3, 22],
[ 4, 4, 3, 6],
[ 4, 4, 3, 8],
[ 4, 4, 3, 12],
[ 4, 4, 3, 14]])
129
是我想要的输出,所以我的代码可以工作,但我正在努力使它尽可能快。我是否应该使用np.array(filter.transpose()
获取filter2
?还有更好的吗
编辑,试图把它说得更清楚:我想要一个索引列表,它们按应用于数组时返回的值排序。要做到这一点,我需要np.where和np.argwhere的输出,我想知道从一个输出切换到另一个输出的最快方法是什么,或者是否有另一种方法可以得到我的结果。查看
argwhere
的代码:
return transpose(asanyarray(a).nonzero())
而where
docs说:
其中(条件[x,y])
如果只给出了条件
,则返回条件.非零()
实际上,两者都使用a.nonzero()
。一个按原样使用,另一个转置
In [933]: x=np.zeros((2,3),int)
In [934]: x[[0,1,0],[0,1,2]]=1
In [935]: x
Out[935]:
array([[1, 0, 1],
[0, 1, 0]])
In [936]: x.nonzero()
Out[936]: (array([0, 0, 1], dtype=int32), array([0, 2, 1], dtype=int32))
In [937]: np.where(x) # same as nonzero()
Out[937]: (array([0, 0, 1], dtype=int32), array([0, 2, 1], dtype=int32))
In [938]: np.argwhere(x)
Out[938]:
array([[0, 0],
[0, 2],
[1, 1]], dtype=int32)
In [939]: np.argwhere(x).T
Out[939]:
array([[0, 0, 1],
[0, 2, 1]], dtype=int32)
argwhere().T
与where
相同,只是在2d而不是元组中
np.transpose(filter)
和np.array(filter).T
看起来同样不错。对于大型数组,在非零
上花费的时间要比在这些转换上花费的时间多得多。也许可以取一个样本分数
,解释一下您想要什么?