2014-01-17 44 views
2

我有以下的Python(NumPy的),我想重構它是清潔劑(也可能更快):是否有更好的方式來改寫這個NumPy的片段

temp = max(value for (x, y), value in np.ndenumerate(cm) if x * y < 100 and (x, y) != (0, 0) and not np.isnan(value)) 

我認爲這是相當清楚的是我想做。總而言之,我嘗試基於值和索引的某些條件過濾2D數組中的某些元素。

任何幫助表示讚賞。

+1

請提供一些示例數據和預期的輸出也是如此。 –

+3

這個問題似乎是脫離主題,因爲它屬於http://codereview.stackexchange.com/ – jonrsharpe

+0

我認爲這是最短的方式,因爲'x * y <100'比較 – zhangxaochen

回答

5
import numpy as np 
from numpy.random import rand, randint 

cm = rand(50, 100) 
cm[randint(0, 50, 4000), randint(0, 100, 4000)] = np.nan 

temp1 = max(value for (x, y), value in np.ndenumerate(cm) if x * y < 100 and (x, y) != (0, 0) and not np.isnan(value)) 

x, y = np.indices(cm.shape) 
mask = (x * y < 100) & (x + y != 0) & (~np.isnan(cm)) 
temp2 = np.max(cm[mask]) 

assert temp1 == temp2 

編輯

max(x+y * value)

np.max((x + y * cm)[mask]) 

np.max(x[mask] + y[mask] * cm[mask]) 
+1

可能會稍微快一點,只需設置'掩碼[0,0] = False而不是檢查每個單元格的x + y!= 0。 – M4rtini

+0

非常感謝!但是,如果我需要「價值」作爲x,y和價值的函數呢?不只是價值。例如,如果我希望獲得最大(x + y *值) –

+0

@FlorentsTselai,您應該更新您的問題以包含樣本輸入和預期輸出,或者可能會用這些詳細信息提出一個新問題。如果你不提供這些信息,人們很難猜測你的數據是什麼樣的(形狀,數據類型等),以及你的結果究竟是什麼。 – YXD

相關問題