我在 numpy 中有一个包含 nans 的 3D 数组。我需要返回沿 0 轴具有最大索引位置的值。答案将简化为二维数组。
关于沿轴查找最大值的索引位置( How to get the index of a maximum element in a numpy array along one axis )有很多问题,但这与我需要的不同。
3D 数组示例:
>>> import numpy as np
>>> foo = np.asarray([[[7,4,6],[4,2,11], [7,8,9], [4,8,2]],[[1,2,3],[np.nan,5,8], [np.nan,np.nan,10], [np.nan,np.nan,7]]])
>>> foo
array([[[ 7., 4., 6.],
[ 4., 2., 11.],
[ 7., 8., 9.],
[ 4., 8., 2.]],
[[ 1., 2., 3.],
[ nan, 5., 8.],
[ nan, nan, 10.],
[ nan, nan, 7.]]])
我以为我已经接近使用 np.where 但它返回所有不是 nan 的元素。不完全是我需要的,因为我想要一个 (4,3)
数组。
>>> zoo = foo[np.where(~np.isnan(foo))]
>>> zoo
array([ 7., 4., 6., 4., 2., 11., 7., 8., 9., 4., 8.,
2., 1., 2., 3., 5., 8., 10., 7.])
我需要的答案是:
>>> ans = np.asarray([[1,2,3], [4,5,8], [7,8,10], [4,8,7]])
>>> ans
array([[ 1, 2, 3],
[ 4, 5, 8],
[ 7, 8, 10],
[ 4, 8, 7]])
编辑:我编辑了 foo 示例数组以使问题更加清晰。
最佳答案
您可以使用np.nanmax
:
>>> np.nanmax(foo, axis=0)
array([[ 7., 4., 6.],
[ 4., 5., 11.],
[ 7., 8., 10.],
[ 4., 8., 7.]])
np.nanmax
函数返回数组的最大值或沿轴的最大值,忽略任何 NaN。
编辑
正如您在评论中正确指出的那样,您需要最大索引处的值,而上面的代码不会返回该值。
相反,您可以使用 apply-along-axis
:
>>> def highest_index(a):
... return a[~np.isnan(a)][-1] # return non-nan value at highest index
>>> np.apply_along_axis(highest_index, 0, foo)
array([[ 1. 2. 3.]
[ 4. 5. 8.]
[ 7. 8. 10.]
[ 4. 8. 7.]])
关于python - 返回 numpy 3D 数组中最高索引的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749558/