Python where()函數與IDL where()函數的比較
本人最近對python的where函數產生了一些疑問,因爲它和IDL中的where函數不太一樣,本文主要就兩種語言的where函數進行簡單的比較。
1 . Python 的where函數在多條件下的判斷
import numpy as np
#首先創建兩個非常大的隨機數組用來做測試
A = np.random.randn(10000, 10000)
B = np.random.randn(10000, 10000) * 10
index = np.where( (A > -1) & (A < 1) & (B > 10) & (B < 20) )
print(type(index), np.shape(index))
看一下np.where的輸出index
#得到滿足條件的下標index是一個兩行N列的元組,第一行爲“行下標”,第二行爲“列下標”
<class 'tuple'> (2, 9280675)
我們在來看一下運行的時間
import numpy as np
import time
#首先創建兩個非常大的隨機數組用來做測試
A = np.random.randn(10000, 10000)
B = np.random.randn(10000, 10000) * 10
start = time.clock()
index = np.where( (A > -1) & (A < 1) & (B > 10) & (B < 20) )
print(type(index), np.shape(index))
elapsed = (time.clock() - start)
print("Time used:",elapsed)
np.where運行的耗費的時間如下:
Time used: 1.8298283580000003
2. IDL在多條件下的判斷
pro test
;創建兩個大型矩陣用來測試
A = RANDOMN(seed, 10000, 10000)
B = RANDOMN(seed, 10000, 10000) * 10
start = systime(/second)
index = where( A gt -1 and A lt 1 and B gt 10 and B lt 20 )
endtime = systime(/second)
print,'running time ', endtime - start
end
看一下IDL的where函數返回的index是一個長整型數組,存儲的是一維的下標
INDEX LONG = Array[9281926]
IDL where函數的運行時間:
running time 0.97099996
如此看來在處理大量數據的時候,IDL 的where函數要比Python快很多。