condition:条件
x:满足条件时函数的输出
y:不满足条件时的输出
>>> import numpy as np
>>> x = np.arange(6).reshape(2, 3)
array([[0, 1, 2],
[3, 4, 5]])
>>> np.where(x > 1, True, False)
array([[False, False, True],
[ True, True, True]])
如果输入的数组都是1-D数组,np.where()等价于:
[xv if c else yv for c, xv, yv in zip(condition, x, y)]
没有x和y参数,则以元组形式输出满足条件的列表索引。
>>> np.where(x > 1)
(array([0, 1, 1, 1], dtype=int64), array([2, 0, 1, 2], dtype=int64))
Find the indices of array elements that are non-zero, grouped by element.
和2类似,但输出的直接是满足要求的元素的坐标索引,不是元组。
>>> np.argwhere(x > 1)
array([[0, 2],
[1, 0],
[1, 1],
[1, 2]], dtype=int64)
参考链接:
1、numpy.where说明文档
2、numpy.argwhere说明文档
1、np.where(condition, x, y)condition:条件x:满足条件时函数的输出y:不满足条件时的输出>>> import numpy as np>>> x = np.arange(6).reshape(2, 3)>>> xarray([[0, 1, 2], [3, 4, 5]])>&g...
q=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
我想获取其中值等于7的那个值的下标,以便于用于其他计算。
如果使用np.where,如:
q=np.arange(0,16,1)
g=np.where(q==7)
print q
print g
运行结果是:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
(array([7]),)
显然(array([7]),)中的数字7我是没法提取出来做运算的,这是一个tuple。
处理方法是:
q=np.arange(0,16,1)
g=np.argwhere(q
在numpy的ndarray类型中,似乎没有直接返回特定索引的方法,我只找到了where函数,但是where函数对于寻找某个特定值对应的索引很有用,对于返回一定区间内值的索引不是很有效,至少我没有弄明白应该如何操作。下面先说一下where函数的用法吧。
(1)where函数的使用场景:
例如现在我生成了一个数组:
import numpy as np
arr=np.array([1,1,1
Find the indices of array elements that are non-zero, grouped by element.- Parameters:
- a : array_like
- Input data.- Returns:
- index_array : ndarray
- Indices of elements that are non-zero. Indices are grouped by element.
a = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a>=5)
print( np.nonzero(a>=5))
[[False False False False]
[ True True True True]
[ True True True True]]
(array([1, 1, 1, 1, 2, 2, 2, 2]), array([0,
1.问题描述
我本来想用np.where去找3维array的二维平面中指定数字2对应的depth维度的值,结果没有搞出来。上网搜索了一下,发现还有一个np.argwhere,解决了问题。
2.np.where与np.argwhere的共同点与区别
① 共同点
都是用来找出满足指定statement的数的index,所谓的statement就是np.where(statement)中的条件表达式,如...
1.np.where(condition,x,y) 当where内有三个参数时,第一个参数表示条件,当条件成立时where方法返回x,当条件不成立时where返回y
2.np.where(condition) 当where内只有一个参数时,那个参数表示条件,当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式
3.多条件时condition,&表...
其中,array([2])表示元素3在数组a中的位置为第3个元素(数组下标从0开始计数)。
如果要查找多个元素的位置,可以将多个元素放在一个列表中,然后使用numpy的in1d函数来判断元素是否在数组中,再使用where函数来查找位置。
例如,假设要查找元素2和4的位置:
b = np.array([2, 4])
index = np.where(np.in1d(a, b))
print(index)
输出结果为:
(array([1, 3]),)
其中,array([1, 3])表示元素2和4在数组a中的位置分别为第2个和第4个元素。