python - 返回 numpy 3D 数组中最高索引的值

标签 python arrays numpy

我在 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/

相关文章:

python - django modelmultiplechoicefield 和 widget checkboxselectmultiple

C# 为什么我可以在函数内部而不是其他任何地方创建标签数组?

python - scipy linprog 中的二元约束

python - pandas.DataFrame 上的成对行操作矩阵

python - 将稠密张量转换为参差不齐的张量

python - 如何在几天、几小时、几周和几个月后迭代一个时间跨度?

python - 快速算法,精确查找二元矩阵中的 k 列,使这些列的总和为 1-向量

python - python 中的柏林噪声

c - 对函数内的结构数组进行排序

c++ - 使用 C++ vector 而不是 C 数组的性能损失