涉及bool运算其实有点绕,官网太简洁,不好懂。
Return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero()
.
1,一维数组情形
import numpy as np
x=np.random.randn(10)
y=np.where(x>0)
print(x)
print(y)
[ 0.53984083 0.81963791 -0.70588564 0.36046388 0.51398193 -1.01097887
-0.97591147 1.5920162 -0.32164574 0.62089156]
(array([0, 1, 3, 4, 7, 9]),)
返回的是索引。
2,二维数组情形
x=np.random.randn(4,4)
y=np.where(x>0)
print(x)
print(y)
print(type(y))
print(np.shape(y))
[[-0.46494093 -0.56619025 0.63625586 0.32151957]
[ 0.27591558 0.48507272 1.08060983 -0.49255729]
[-0.43826664 0.14835337 1.07969824 -0.39603228]
[ 0.12159492 0.149116 0.26444495 0.99560979]]
(array([0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 3]), array([2, 3, 0, 1, 2, 1, 2, 0, 1, 2, 3]))
<class 'tuple'>
(2, 11)
返回的是第一个分量是一维索引,类似(x,y)坐标的x,第二个分量是二维的索引,类似(x,y)坐标的y。
3,三维数组情形
[[[-0.37917805 -1.53885845 -0.39460989 0.67751276]
[-0.92359847 0.93436404 -0.51285372 -0.89198071]
[ 0.41684439 -0.70988507 -0.50356141 -2.40755229]
[-1.02122016 0.610473 0.36177794 -0.03001534]]
[[-0.63599081 -1.28134616 1.40271032 0.067887 ]
[ 1.57162956 1.39242353 -0.37710681 -1.50463798]
[ 1.343914 -1.09522626 -0.9958491 2.72785346]
[-0.69637549 0.61299699 0.49142939 0.50537266]]]
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), array([0, 1, 2, 3, 3, 0, 0, 1, 1, 2, 2, 3, 3, 3]), array([3, 1, 0, 1, 2, 2, 3, 0, 1, 0, 3, 1, 2, 3]))
<class 'tuple'>
(3, 14)
第一维是垂直屏幕,第二维是横,第三维是竖。
4,如果是np.where(x)等效于np.where(x!=0)
x=np.random.randn(4,4)
z=np.where(x)
print(z)
(array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]), array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))
a = np.array(([True,False,True],[False,False,False]))
b = np.where(a)
print(b)
(array([0, 0]), array([0, 2]))
5,np.where(condition,[x,y])
条件真,数组元素改成x,条件假,数组元素改成y。
x=np.random.randn(3,3)
y=np.where(x>0,1,-1)
print(x)
print(y)
[[ 0.00369148 0.88969299 -2.18486436]
[ 2.00694134 -0.43627724 -1.30865904]
[-1.39606338 -2.20609871 1.71420687]]
[[ 1 1 -1]
[ 1 -1 -1]
[-1 -1 1]]
np.where([[True, False], [True, True]],1,-1)
array([[ 1, -1],
[ 1, 1]])
np.where([[True, False], [True, True]],[[1, 2], [3, 4]],[[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
6,经典应用
xx,yy,zz= np.where(Mask)
获取mask中非零元素的x,y,z坐标。
更多数学原理小文请关注公众号:未名方略