我知道Python列表有一个方法可以返回某个对象的第一个索引:
>>> xs = [1, 2, 3]
>>> xs.index(2)
1
NumPy数组也有类似的东西吗?
我知道Python列表有一个方法可以返回某个对象的第一个索引:
>>> xs = [1, 2, 3]
>>> xs.index(2)
1
NumPy数组也有类似的东西吗?
当前回答
用ndindex
样本数组
arr = np.array([[1,4],
[2,3]])
print(arr)
...[[1,4],
[2,3]]
创建一个空列表来存储索引和元素元组
index_elements = []
for i in np.ndindex(arr.shape):
index_elements.append((arr[i],i))
将元组列表转换为字典
index_elements = dict(index_elements)
键是元素,值是元素 索引——使用键来访问索引
index_elements[4]
output
... (0,1)
其他回答
另一个之前没有提到的选项是bisect模块,它也适用于列表,但需要一个预先排序的列表/数组:
import bisect
import numpy as np
z = np.array([104,113,120,122,126,138])
bisect.bisect_left(z, 122)
收益率
3
Bisect还会在您要查找的数字在数组中不存在时返回一个结果,以便将该数字插入正确的位置。
用ndindex
样本数组
arr = np.array([[1,4],
[2,3]])
print(arr)
...[[1,4],
[2,3]]
创建一个空列表来存储索引和元素元组
index_elements = []
for i in np.ndindex(arr.shape):
index_elements.append((arr[i],i))
将元组列表转换为字典
index_elements = dict(index_elements)
键是元素,值是元素 索引——使用键来访问索引
index_elements[4]
output
... (0,1)
只是添加一个非常高性能和方便的numba替代np。Ndenumerate来查找第一个索引:
from numba import njit
import numpy as np
@njit
def index(array, item):
for idx, val in np.ndenumerate(array):
if val == item:
return idx
# If no item was found return None, other return types might be a problem due to
# numbas type inference.
这非常快,并且自然地处理多维数组:
>>> arr1 = np.ones((100, 100, 100))
>>> arr1[2, 2, 2] = 2
>>> index(arr1, 2)
(2, 2, 2)
>>> arr2 = np.ones(20)
>>> arr2[5] = 2
>>> index(arr2, 2)
(5,)
这比任何使用np的方法都要快得多(因为它使操作短路)。Where或np. non0。
然而np。Argwhere也可以优雅地处理多维数组(你需要手动将它转换为元组,而且不会短路),但如果没有找到匹配,它就会失败:
>>> tuple(np.argwhere(arr1 == 2)[0])
(2, 2, 2)
>>> tuple(np.argwhere(arr2 == 2)[0])
(5,)
从np.where()中选择第一个元素的替代方法是使用生成器表达式和enumerate,例如:
>>> import numpy as np
>>> x = np.arange(100) # x = array([0, 1, 2, 3, ... 99])
>>> next(i for i, x_i in enumerate(x) if x_i == 2)
2
对于二维数组,可以这样做:
>>> x = np.arange(100).reshape(10,10) # x = array([[0, 1, 2,... 9], [10,..19],])
>>> next((i,j) for i, x_i in enumerate(x)
... for j, x_ij in enumerate(x_i) if x_ij == 2)
(0, 2)
这种方法的优点是,它在找到第一个匹配后停止检查数组的元素,而np。Where检查所有元素是否匹配。如果在数组的前面有匹配,生成器表达式会更快。
如果你想用它作为其他东西的索引,如果数组是可广播的,你可以使用布尔索引;不需要显式索引。要做到这一点,绝对最简单的方法是基于真值进行索引。
other_array[first_array == item]
任何布尔运算都可以:
a = numpy.arange(100)
other_array[first_array > 50]
非零方法也接受布尔值:
index = numpy.nonzero(first_array == item)[0][0]
两个0分别表示索引元组(假设first_array是1D)和索引数组中的第一项。