获取满足我的条件的np.array索引的最快方法

问题描述 投票:-1回答:1

我正在寻找最快的方法来获取符合我的标准的矩阵元素的索引。我有一个(7,7)np.array(名为“ board”),其中包含从0-> 400的int16。我想查找例如等于300的元素的索引。

我尝试了很多技术,到目前为止最快的是np.where(board == 300)

我正在尝试优化的功能:

    def is_end(self, board):
        ind = np.where((board > 300) & (board - 300 < 100))
        try:
            victoriousPlayer = board[ind[0][0], ind[1][0]] % 100 // 10
            return victoriousPlayer
        except:
            return -1

因为我使用此功能数以万计,所以我需要它尽可能快地运行。

python performance numpy optimization indices
1个回答
0
投票

在这种情况下,您似乎不需要索引,只需一个掩码。

ind = np.where((board > 300) & (board - 300 < 100))
victoriousPlayer = board[ind[0][0], ind[1][0]] % 100 // 10

相当于

victoriousPlayer = board[(board  > 300) & (board - 300 < 100)][0] % 100 // 10
© www.soinside.com 2019 - 2024. All rights reserved.