我有一个numpy数组:
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行应该返回Nan.
第2行应返回1.
第3行应该返回3.
我不知道如何在argmax上对此进行调整.
解决方法:
这是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.])
标签:python,numpy
来源: https://codeday.me/bug/20190522/1154539.html