numpy.where()用法詳解

numpy.where()有兩種用法
1、np.where(condition, x, y)
滿足條件(condition),輸出x,不滿足輸出y

#1
>>> aa = np.arange(10)
>>> np.where(aa,1,-1)
array([-1,  1,  1,  1,  1,  1,  1,  1,  1,  1])  # 0爲False,所以第一個輸出-1
#2
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1])
#3
>>> np.where([[True,False], [True,True]],    # 官網上的例子
			 [[1,2], [3,4]],
             [[9,8], [7,6]])
array([[1, 8],
	   [3, 4]])
#4
>>> a = 10
>>> np.where([[a > 5,a < 5], [a == 10,a == 7]],
             [["chosen","not chosen"], ["chosen","not chosen"]],
             [["not chosen","chosen"], ["not chosen","chosen"]])

array([['chosen', 'chosen'],
       ['chosen', 'chosen']], dtype='<U10')

2、np.where(condition)
只有條件 (condition),沒有x和y,則輸出滿足條件 (即非0) 元素的座標 (等價於numpy.nonzero)。這裏的座標以tuple的形式給出,通常原數組有多少維,輸出的tuple中就包含幾個數組,分別對應符合條件元素的各維座標。

#1 
>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5)				# 返回滿足條件元素的索引
(array([2, 3, 4]),)   
>>> a[np.where(a > 5)]  			# 等價於 a[a>5]
array([ 6,  8, 10])
#2
>>> np.where([[0, 1], [1, 0],[4,6])
(array([0, 1, 2, 2]), array([1, 0, 0, 1]))#輸出兩個1的座標
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章