1

我有一个np.array

x = np.array([[1,2], [4,5], [4,6], [5,4], [4,5]])

现在我想要 x 等于[4,5]( -> [1, 4]) 的索引。操作员==以不同的方式工作:

x == [4,5]
array([[False, False],
       [ True,  True],
       [ True, False],
       [False, False],
       [ True,  True]], dtype=bool)

但我想要类似的东西[False, True, False, False, True]。可以做and吗?

通常数组非常大,我必须做很多次,所以我需要一个非常快速的方法。

4

2 回答 2

4

这应该是numpy方式:

x = np.array([[1,2], [4,5], [4,6], [5,4], [4,5]])
(x == [4,5]).all(1)

#out: array([False,  True, False, False,  True], dtype=bool)
于 2012-05-22T09:21:16.387 回答
0

没有使用 numpy 的经验,但这适用于标准数组:

x = [[1, 2], [4, 5], [4, 6], [5, 4], [4, 5]]

indices = [i for i, v in enumerate(x) if v == [4, 5]]
# gives [1, 4]

matches = [v == [4, 5] for v in x]
# gives [False, True, False, False, True]
于 2012-05-22T08:52:37.847 回答