从阿尔格到哪里?

2024-09-26 22:44:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在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,  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()得到{}?还有更好的吗?在

编辑,试着把它说得更清楚:我想要一个索引的列表,按它们应用于数组时返回的值排序。为此,我需要np.哪里以及np.argwhere,我想知道从一个输出切换到另一个输出的最快方法是什么,或者是否有另一种方法可以得到我的结果。在


Tags: 方法代码in格式npfilteroutwhere
1条回答
网友
1楼 · 发布于 2024-09-26 22:44:19

查看argwhere的代码:

return transpose(asanyarray(a).nonzero())

where文档说:

where(condition, [x, y]) If only condition is given, return condition.nonzero().

实际上,两者都使用a.nonzero()。一种是按原样使用,另一种则是调换它。在

^{pr2}$

argwhere().T与{}相同,只是在2d而不是元组中。在

np.transpose(filter)和{}看起来同样不错。对于一个大数组,nonzero所花费的时间远大于这些转换所花费的时间。在

相关问题 更多 >

    热门问题