如何找到Numpy数组中的值的索引
在这篇文章中,我们将使用where()方法查找Numpy数组中的元素的索引。它是用来指定条件中指定的特定元素的索引。
语法:numpy.where(condition[, x, y])
获取一个给定值的索引位置
在这里,我们找到3的所有索引和3的第一次出现的索引。
# import numpy package
import numpy as np
# create an numpy array
a = np.array([1, 2, 3, 4, 8, 6, 7, 3, 9, 10])
# display index value of 3
print("All index value of 3 is: ", np.where(a == 3))
print("First index value of 3 is: ",np.where(a==3)[0][0])
输出:
All index value of 3 is: (array([2, 7], dtype=int64),)
First index value of 3 is: 2
打印几个值的第一个索引位置
在这里,我们要打印所有存在于数值阵列中的数值的索引号。
# import numpy package
import numpy as np
# create an numpy array
a = np.array([1, 2, 3, 4, 8, 6, 2, 3, 9, 10])
values = np.array([2, 3, 10])
# index of first occurrence of each value
sorter = np.argsort(a)
print("index of first occurrence of each value: ",
sorter[np.searchsorted(a, values, sorter=sorter)])
输出:
index of first occurrence of each value: [1 2 9]
根据多个条件获取元素的索引。
获取数值小于20且大于12的元素的索引
# Create a numpy array
a = np.array([11, 12, 13, 14, 15, 16, 17, 15,
11, 12, 14, 15, 16, 17, 18, 19, 20])
# Get the index of elements with value less
# than 20 and greater than 12
print("Index of elements with value less\
than 20 and greater than 12 are: \n",
np.where((a > 12) & (a < 20)))
输出:
Index of elements with value less than 20 and greater than 12 are:
(array([ 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15], dtype=int64),)
在的Python循环中获取元素的索引
创建一个NumPy数组,并对数组进行迭代,将数组中的元素与给定的数组进行比较。如果元素匹配则打印索引。
import numpy as np
# create numpy array elements
a = np.array([2, 3, 4, 5, 6, 45, 67, 34])
# display element index where value = 45
index_of_element = -1
for i in range(a.size):
if a[i] == 45:
index_of_element = i
break
if index_of_element != -1:
print("element index : ", index_of_element)
else:
print("The element not present")
输出:
element index : 5