我的np数组列表中有元组,例如np.array [(0,1),(2,5),...]
现在,我要搜索某个值的索引。但是我只知道元组的左侧。我发现获取值索引(如果同时拥有)的方法如下:
x = np.array(list(map(lambda x: x== (2, 5), groups)))
print(np.where(x))
但是,如果我只知道x ==(2,)但不知道正确的数字,该如何搜索?
如https://numpy.org/doc/stable/reference/generated/numpy.where.html#numpy.where中所述,最好np.nonzero
直接使用。我还建议阅读有关NumPy对布尔掩码的使用的信息。您问题的答案是:
import numpy as np
i = 0 # index of number we're looking for
j = 2 # number we're looking for
mask = x[:,i] == j # Generate a binary/boolean mask for this array and this comparison
indices = np.nonzero(mask) # Find indices where x==(2,_)
print(indices)
在NumPy中,通常最好避免使用上述循环。相反,您应该使用向量化操作。因此,请尽量避免list(map())
使用此处使用的结构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句