numpy查找元素索引
时间: 2023-11-04 17:04:40 浏览: 44
Sure, I can help you with that! To find the index of an element in a numpy array, you can use the `numpy.where` function. Here's an example:
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
idx = np.where(arr == 3)
print(idx)
```
This will output `(array([2]),)`, which means that the index of the element `3` in the array is `2`.
相关问题
numpy.ndarray查找元素index
可以使用numpy.where()函数来查找numpy数组中指定元素的索引位置。
例如,对于一个一维数组a,我们可以使用以下代码来查找元素值为x的索引位置:
```
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 5])
x = 5
indices = np.where(a == x)[0]
print(indices)
```
该代码会输出:[4, 6],这表示元素值为5的元素在数组a中的索引位置为4和6。
如果我们想查找二维数组中某个元素的索引位置,可以使用numpy.nonzero()函数:
```
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
x = 5
indices = np.nonzero(a == x)
print(indices)
```
该代码会输出:(array([1]), array([1])),这表示元素值为5的元素在数组a中的索引位置为(1, 1)。其中,第一个数组表示行索引,第二个数组表示列索引。
numpy返回索引的函数
numpy提供了很多返回索引的函数,下面列举一些常用的:
1. argmin(arr, axis=None, out=None): 返回数组中最小值的索引。
2. argmax(arr, axis=None, out=None): 返回数组中最大值的索引。
3. nonzero(arr): 返回非零元素的索引值。
4. where(condition[, x, y]): 根据条件返回相应元素的索引值。
5. searchsorted(a, v[, side='left', sorter=None]): 在已排序的数组中查找v的插入点,返回索引值。
6. sort(a[, axis, kind, order]): 返回数组排序后的索引值。
7. lexsort(keys[, axis]): 返回多个键的排序后的索引值。
8. argsort(a[, axis, kind, order]): 返回数组排序后的索引值。
9. partition(a, kth[, axis, kind, order]): 返回数组kth小的元素的索引值。
以上是一些常用的返回索引的函数,还有其他的函数可以查阅numpy官方文档。