在矩阵中逐列查找最小值及其索引

3
我有一个问题,看起来很简单,但却让我头疼了一阵。 问题是我在用Python编程(我对它还相对陌生),并且我在寻找一个使用numpy等价于Matlab中的max(min)函数的方法。
我的目标是从矩阵中获取最小值及其索引。
为了便于理解,举个例子,假设这是矩阵:
arr2D = np.array([[11, 12, 13, 34],
                  [14, 15, 16, 3],
                  [17, 15, 11, 1],
                  [7,   5, 11, 4],
                  [1,  12,  4, 4],
                  [12, 14, 15,-3]])

在Matlab中,我会这样做:
[local_max, index] = min(arr2D)

我希望对于矩阵中的每一列,都能得到其最小值以及其索引。

参考以下链接中的内容:这里这里,尝试在Python中重复执行此操作,使用以下代码:

print(np.where(arr2D == np.amin(arr2D, axis = 0)))   # axis 0 is for columns

我得到以下输出:

(array([3, 4, 4, 5]), array([1, 0, 2, 3]))  

这并不是我想要的!

预期输出应该是:

[1, 4]   # Meaning the minimum value is 1 and it is in row 4 for the first column
[5, 3]   # Meaning the minimum value is 5 and it is in row 3 for the second column
[4, 4]   # Meaning the minimum value is 4 and it is in row 4 for the third column
[-3, 5]  # Meaning the minimum value is -3 and it is in row 5 for the last column

我无法使用获取的输出结果,具体原因如下:

print(np.where(arr2D == np.amin(arr2D, axis = 0)))

可能是我没理解输出结果,或这并不是获取Matlab中等价函数max(min)的正确方法。

你能帮我吗?

更新: 我忘记说这个矩阵是浮点数而不是整数。 我只是为了举例使用整数。


1
第一列最小值不应该是 1,第四列应该是 -3 吗? - Psidom
你是对的!我已经纠正了它...感谢你指出。 - Dave
2个回答

2

np.aminnp.min返回沿轴的最小值。

np.amin(arr2D, axis=0)

输出:

array([ 1,  5,  4, -3])

np.argmin returns the indices

np.argmin(arr2D, axis=0)

输出:

array([4, 3, 4, 5])

为了得到期望的输出,您可以使用 np.vstack 并转置数组。
np.vstack([np.amin(arr2D, axis=0), np.argmin(arr2D, axis=0)]).T

输出:

array([[ 1,  4],
       [ 5,  3],
       [ 4,  4],
       [-3,  5]])

2
请使用以下代码(您可以将其简单地打包成一个函数):
import numpy as np

arr2D = np.array([[11, 12, 13, 34],
            [14, 15, 16, 3],
            [17, 15, 11, 1],
            [7,   5, 11, 4],
            [1,  12,  4, 4],
            [12, 14, 15,-3]])

flat = arr2D.flatten()
arrayIndex = flat.tolist().index(min(flat))

// results
rowIndex = int(minIndex/arr2D.shape[0])
columnIndex = minIndex % arr2D.shape[1]

非常感谢!我发现使用 'flatten()' 的方式不是很直观,但它似乎可以工作。 - Dave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接