Python Numpy通过搜索2个值来查找由5个值组成的数组的行索引

2024-09-30 16:40:06 发布

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

如果这个标题不是新名词的话。在

假设我们有一个numpy数组作为世界地图。 参数是(x y r g b)-都是int16

示例:

a = np.array([[  0,   0,   0, 255,   0], #index 0
              [  0,   1,   0,   0, 255], #index 1
              [  0,   2,   0, 255,   0]]) #index 2

现在我们要找到x和y值(0,2)的行的索引值,因此是索引为2的行。在

^{pr2}$

在不输入其他值(rgb)的情况下,我如何做到这一点?基本上,我们正在搜索一个包含两个值的五值行-我该怎么做?在


Tags: numpy标题示例参数indexnp情况rgb
2条回答

您可以将行切片到第二列,并检查它们是否等于[0,2]。然后使用^{}设置axis到{}将满足所有条件的设置为True,并使用布尔数组索引ndarray

a = np.array([[  0,   0,   0, 255,   0],
              [  0,   1,   0,   0, 255],
              [  0,   2,   0, 255,   0]])

a[(a[:,:2] == [0,2]).all(1)]
# array([[  0,   2,   0, 255,   0]])

以下是您的数据:

import numpy as np

arr = np.array([[  0,   0,   0, 255,   0],
              [  0,   1,   0,   0, 255],
              [  0,   2,   0, 255,   0]])

a,b = 0,2 # [a,b] is what we are looking for, in the first two cols

下面是获取包含[a,b]的行索引的解决方案:

^{pr2}$

输出:

2

说明:

了解其工作原理的最佳方法是打印每个部分:

print (arr[:,0]==[a])

输出:

[ True True True]

print (arr[:,1]==[b])

输出:

[False False True]

print (np.logical_and(arr[:,0]==[a],arr[:,1]==[b]))
# print (np.logical_and([ True  True  True], [False False  True]))

输出:

[假-假-真]

相关问题 更多 >