如果列全部为nan,则使numpy.nanargmin返回nan [英] making numpy.nanargmin return nan if column is all nan
问题描述
是否可以使用numpy.nanargmin
,以便在其中仅包含nan的列上返回numpy.nan
.现在,当发生这种情况时,它会引发一个ValueError
.而且我不能使用numpy.argmin
,因为当列中只有少数Nan时,它将失败.
Is it possible to use numpy.nanargmin
, so that it returns numpy.nan
, on columns where there are only nans in them. Right now, it raises a ValueError
, when that happens. And i cant use numpy.argmin
, since that will fail when there are only a few nans in the column.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanargmin.html 表示ValueError
对于全南切片都适用.在那种情况下,我希望它返回numpy.nan(只是为了进一步用nans掩盖非数据")
http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanargmin.html says that the ValueError
is raised for all-nan slices. In that case, i want it to return numpy.nan (just to further mask the "non-data" with nans)
这下一点可以做到这一点,但是它非常慢,而且不是真正的pythonic:
this next bit does this, but is super-slow and not really pythonic:
for i in range(R.shape[0]):
bestindex = numpy.nanargmin(R[i,:])
if(numpy.isnan(bestindex)):
bestepsilons[i]=numpy.nan
else:
bestepsilons[i]=epsilon[bestindex]
下一点也可以使用,但前提是不涉及all-nan列:
This next bit works too, but only if no all-nan columns are involved:
ar = numpy.nanargmin(R, axis=1)
bestepsilons = epsilon[ar]
所以理想情况下,我希望最后一点也能与全南列一起使用
So ideally i would want this last bit to work with all-nan columns as well
推荐答案
找到了解决方案:
# makes everything nan to start with
bestepsilons1 = numpy.zeros(R.shape[0])+numpy.nan
# finds the indices where the entire column would be nan, so the nanargmin would raise an error
d0 = numpy.nanmin(R, axis=1)
# on the indices where we do not have a nan-column, get the right index with nanargmin, and than put the right value in those points
bestepsilons1[~numpy.isnan(d0)] = epsilon[numpy.nanargmin(R[~numpy.isnan(d0),:], axis=1)]
这基本上是一种解决方法,只将nanargmin放在不会产生错误的地方,因为在那些地方,我们希望所得的索引始终是nan
This basically is a workaround, by only taking the nanargmin on the places where it will not give an error, since at those places we want the resulting index to be a nan anyways
这篇关于如果列全部为nan,则使numpy.nanargmin返回nan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!