2017-09-03 59 views
0

我希望有人能提供一些關於numpy.where()函數如何工作的說明。在嘗試了幾個不同的輸入之後,我無法把頭圍住它。以低於第一實施例,輸出:當numpy.where(array condition,array1,array2)輸入時,numpy.where()如何工作?

np.where([True,False],[1,0],[3,4]) 

是:

array([1, 4]) 

究竟如何布爾值的陣列被施加到陣列[1,0][3,4],得到輸出?

一些額外測試的

結果如下所示:

import numpy as np 

np.where([True,False],[1,0],[3,4]) 
Out[129]: array([1, 4]) 

np.where([True,False],[1,0],[6,4]) 
Out[130]: array([1, 4]) 

np.where([True,False],[1,0],[0,0]) 
Out[131]: array([1, 0]) 

np.where([True,False],[0,0],[0,0]) 
Out[132]: array([0, 0]) 

np.where([True,False],[1,0],[0,12]) 
Out[133]: array([ 1, 12]) 

np.where([True,False],[1,6],[4,12]) 
Out[134]: array([ 1, 12]) 

np.where([True,True],[1,6],[4,12]) 
Out[135]: array([1, 6]) 

np.where([False,False],[1,6],[4,12]) 
Out[136]: array([ 4, 12]) 

np.where([True,False],[1,0],[3,4]) 
Out[137]: array([1, 4]) 

np.where([True,True],[1,0],[3,4]) 
Out[138]: array([1, 0]) 

np.where([True,True],[1,0],[3,4]) 
Out[139]: array([1, 0]) 

np.where([True,False],[1,0],[3,4]) 
Out[140]: array([1, 4]) 

回答

1

如果你給3個參數來np.where的第一個參數是,如果在結果中的對應值是從第二個參數採取決定的條件(如果條件中的值是True)或來自第三個參數(如果條件中的值是False)。

所以當所有值都是True它將是第一個參數的副本,如果所有值都是False它將是第二個參數的副本。如果他們混合,它將是一個組合。

認爲它是一個更復雜的版本:

def where(condition, x, y): 
    result = [] 
    for idx in range(len(condition)): 
     if condition[idx] == True: 
      result.append(x[idx]) 
     else: 
      result.append(y[idx]) 
    return result 

這個函數,當然是慢得多(即使是最快的純Python等值貨幣),也不支持廣播或多維數組和一個參數形式,但我希望它有助於理解np.where的3個參數形式。

+0

非常感謝。這正好解決了我的困惑。 – Sisyphus

相關問題