我是 Numpy 的新手。我想找到等于一组值的元素索引。例如,我知道这行得通:
>>> x = np.array([[0, 1], [2, 3], [4, 5]])
>>> x
array([[0, 1],
[2, 3],
[4, 5]])
>>> x[np.where(x[:,0] == 2)]
array([[2, 3]])
但是为什么这行不通呢?我想这应该是一个直接的扩展。没有?
>>> x[np.where(x[:,0] == [2,4])]
array([], shape=(0, 2), dtype=int64)
请您参考如下方法:
== 不是那样工作的;当给定两个不同形状的数组时,它会尝试根据 broadcasting rules 广播比较结果。 .
如果要确定数组的哪些元素在元素列表中,则需要 in1d :
>>> x = numpy.arange(9).reshape((3, 3))
>>> numpy.in1d(x.flat, [2, 3, 5, 7])
array([False, False, True, True, False, True, False, True, False], dtype=boo
l)
>>> numpy.in1d(x.flat, [2, 3, 5, 7]).reshape(x.shape)
array([[False, False, True],
[ True, False, True],
[False, True, False]], dtype=bool)
