我有以下的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數組中的某些元素。
任何幫助表示讚賞。
我有以下的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數組中的某些元素。
任何幫助表示讚賞。
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])
請提供一些示例數據和預期的輸出也是如此。 –
這個問題似乎是脫離主題,因爲它屬於http://codereview.stackexchange.com/ – jonrsharpe
我認爲這是最短的方式,因爲'x * y <100'比較 – zhangxaochen