在Python中,我们可以使用.index()
方法获取数组中值的索引。
但是对于NumPy数组,当我尝试执行以下操作时:
decoding.index(i)
我得到:
AttributeError: 'numpy.ndarray'对象没有属性'index'
如何在NumPy数组上执行此操作?
使用np.where
来获取给定条件为True
的索引。
示例:
对于名为a
的2D np.ndarray
:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
对于一个一维数组:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
请注意,这也适用于像>=
、<=
、!=
等条件...。index()
方法的np.ndarray
子类:class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
测试:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1
这正是你想要的。
我在这两种实现 NumPy 数组索引的方式之间犹豫不决:
idx = list(classes).index(var)
idx = np.where(classes == var)
两种方法所使用的字符数相同,但第一种方法返回一个int
,而不是一个numpy.ndarray
。
a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]
import numpy_indexed as npi
assert all(i == npi.indices(a, b))
numpy.nonzero()
,或数组的nonzero()
方法。import numpy as np
A = np.array([[2,4],
[6,2]])
index= np.nonzero(A>1)
OR
(A>1).nonzero()
输出:
(array([0, 1]), array([1, 0]))
输出的第一个数组表示行索引,第二个数组表示相应的列索引。
a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)
np.where
的输出始终是一个tuple
。如果我使用i = np.where(...)
,那么我的变量i
将是一个tuple
对象。 - Saullo G. P. Castro