numpy中argwhere是干什么的
时间: 2024-01-25 20:03:12 浏览: 116
numpy中的argwhere函数是用来找到数组中满足条件的元素的索引。它返回一个数组中满足条件的元素的索引,这些索引是以元组的形式给出的,每个元组表示一个符合条件的元素的位置。例如,如果有一个数组arr = [1, 2, 3, 4, 5, 6],然后我们可以使用argwhere函数找到所有大于3的元素的索引,如下所示:
```
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
indices = np.argwhere(arr > 3)
print(indices)
```
这将输出:
```
[[3]
[4]
[5]]
```
其中,每个元素都是一个索引元组,表示符合条件的元素的位置。在这个例子中,arr[3],arr[4]和arr[5]都大于3,因此argwhere返回这些元素的索引。
相关问题
numpy where argwhere
numpy中的where函数和argwhere函数都可以用于根据条件返回数组中的元素索引。其中,where函数返回满足条件的元素的索引,而argwhere函数返回满足条件的元素的坐标。
具体来说,where函数的用法如下:
```python
numpy.where(condition[, x, y])
```
其中,condition是一个布尔型数组,x和y是可选参数,表示满足条件和不满足条件时返回的值。如果只传入condition,则返回满足条件的元素的索引。
argwhere函数的用法如下:
```python
numpy.argwhere(a)
```
其中,a是一个数组,返回满足条件的元素的坐标。
举个例子:
```python
import numpy as np
a = np.array([1, 2, 3, 4, 5])
condition = a > 3
# 使用where函数返回满足条件的元素的索引
print(np.where(condition)) # 输出 (array([3, 4]),)
# 使用argwhere函数返回满足条件的元素的坐标
print(np.argwhere(condition)) # 输出 [[3], [4]]
```
Numpy.argwhere
Numpy.argwhere 函数返回一个数组中非零元素的索引,这些索引可以是多维的。例如,如果有一个二维的数组 arr,那么 numpy.argwhere(arr) 将返回一个包含非零元素索引的二维数组,其中每个非零元素索引均表示为一个长度为 2 的元组。下面是一个示例:
```python
import numpy as np
arr = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
print(arr)
# Output:
# [[0 1 0]
# [1 0 0]
# [0 0 1]]
indices = np.argwhere(arr)
print(indices)
# Output:
# [[0 1]
# [1 0]
# [2 2]]
```
在上面的示例中,我们首先创建了一个二维的 numpy 数组 arr,并打印了它的值。然后,我们使用 numpy.argwhere 函数获取了 arr 中的非零元素索引,并将它们存储在 indices 变量中。最后,我们打印了 indices 的值,它包含了 arr 中所有非零元素的索引。
阅读全文
相关推荐












