在numpy数组中查找具有最高平均值的行

Dan*_*ray 6 python arrays numpy

给出以下数组:

complete_matrix = numpy.array([
    [0, 1, 2, 4],
    [1, 0, 3, 5],
    [2, 3, 0, 6],
    [4, 5, 6, 0]])
Run Code Online (Sandbox Code Playgroud)

我想确定平均值最高的行,不包括对角线零.因此,在这种情况下,我将能够识别出complete_matrix[:,3]具有最高平均值的行.

kjo*_*ppy 7

请注意,零的存在不会影响哪一行具有最高平均值,因为所有行具有相同数量的元素.因此,我们只取每行的均值,然后询问最大元素的索引.

#Take the mean along the 1st index, ie collapse into a Nx1 array of means
means = np.mean(complete_matrix, 1)
#Now just get the index of the largest mean
idx = np.argmax(means)
Run Code Online (Sandbox Code Playgroud)

idx现在是具有最高均值的行的索引!


ars*_*jii 5

您无需担心0s,它们不应该影响平均值的比较方式,因为每行中可能会有一个。因此,您可以执行以下操作来获取平均值最高的行的索引:

>>> import numpy as np 
>>> complete_matrix = np.array([
...     [0, 1, 2, 4],
...     [1, 0, 3, 5],
...     [2, 3, 0, 6],
...     [4, 5, 6, 0]])
>>> np.argmax(np.mean(complete_matrix, axis=1))
3
Run Code Online (Sandbox Code Playgroud)

参考: