In Python we can get the index of a value in an array by using .index(). How can I do it with a NumPy array?
在Python中,我们可以使用.index()获取数组中值的索引。我怎么能用NumPy数组做到这一点?
When I try to do
当我尝试做的时候
decoding.index(i)
it says that the NumPy library doesn't support this function. Is there a way to do it?
它说NumPy库不支持这个功能。有办法吗?
3 个解决方案
#1
43
Use np.where
to get the indices where a given condition is True
.
使用np.where获取给定条件为True的索引。
Examples:
例子:
For a 2D np.ndarray
:
对于2D np.ndarray:
i, j = np.where(a == value)
For a 1D array:
对于1D阵列:
i, = np.where(a == value)
Which works for conditions like >=
, <=
, !=
and so forth...
适用于> =,<=,!=等条件......
You can also create a subclass of np.ndarray
with an index()
method:
您还可以使用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)
Testing:
测试:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
#2
7
You can convert a numpy array to list and get its index .
您可以将numpy数组转换为list并获取其索引。
for example
例如
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
i is just what you want.
我就是你想要的。
#3
4
I'm torn between these two ways of implementing an index of a NumPy array:
我在实现NumPy数组索引的这两种方式之间徘徊:
idx = list(classes).index(var)
idx = np.where(classes == var)
Both take the same number of characters, but the second method returns an int
, instead of a nparray
.
两者都使用相同数量的字符,但第二种方法返回int,而不是nparray。
#1
43
Use np.where
to get the indices where a given condition is True
.
使用np.where获取给定条件为True的索引。
Examples:
例子:
For a 2D np.ndarray
:
对于2D np.ndarray:
i, j = np.where(a == value)
For a 1D array:
对于1D阵列:
i, = np.where(a == value)
Which works for conditions like >=
, <=
, !=
and so forth...
适用于> =,<=,!=等条件......
You can also create a subclass of np.ndarray
with an index()
method:
您还可以使用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)
Testing:
测试:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
#2
7
You can convert a numpy array to list and get its index .
您可以将numpy数组转换为list并获取其索引。
for example
例如
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
i is just what you want.
我就是你想要的。
#3
4
I'm torn between these two ways of implementing an index of a NumPy array:
我在实现NumPy数组索引的这两种方式之间徘徊:
idx = list(classes).index(var)
idx = np.where(classes == var)
Both take the same number of characters, but the second method returns an int
, instead of a nparray
.
两者都使用相同数量的字符,但第二种方法返回int,而不是nparray。