2017-02-10 49 views
4

我有一個numpy的數組:,最大numpy的argmax少於一定數目

myArray 
array([[ 1. ,  nan,  nan,  nan,  nan], 
     [ 1. ,  nan,  nan,  nan,  nan], 
     [ 0.63 , 0.79 , 1. ,  nan,  nan], 
     [ 0.25 , 0.4 , 0.64 , 0.84 ,  nan]]) 

我需要找到的每一行,爲最大值的列數,但最多有小於1

在上面的數組中,行0,1應該返回Nan。

第2行應返回1.

第3行應該返回3.

我不知道如何在argmax條件此。

回答

3

下面是與np.where一種方法 -

m = a < 1 # Mask of elems < 1 and non-NaNs 

# Set NaNs and elems > 1 to global minimum values minus 1, 
# so that when used with argmax those would be ignored 
idx0 = np.where(m, a,np.nanmin(a)-1).argmax(1) 

# Look for rows with no non-NaN and < 1 elems and set those in o/p as NaNs 
idx = np.where(m.any(1), idx0, np.nan) 

採樣運行 -

In [97]: a 
Out[97]: 
array([[ 1. , nan, nan, nan, nan], 
     [ 1. , nan, nan, nan, nan], 
     [ 0.63, 0.79, 1. , nan, nan], 
     [ 0.25, 0.4 , 0.64, 0.84, nan]]) 

In [98]: m = a < 1 

In [99]: idx0 = np.where(m, a,np.nanmin(a)-1).argmax(1) 

In [100]: idx0 
Out[100]: array([0, 0, 1, 3]) 

In [101]: np.where(m.any(1), idx0, np.nan) 
Out[101]: array([ nan, nan, 1., 3.]) 
相關問題