如何找到一个numpy矩阵的最小值? (在这种情况下) [英] How do I find the minimum of a numpy matrix? (In this particular case)

查看:145
本文介绍了如何找到一个numpy矩阵的最小值? (在这种情况下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的numpy矩阵

I have a numpy matrix as follows

[['- A B C D E']
['A 0 2 3 4 5']
['B 2 0 3 4 5']
['C 3 3 0 4 5']
['D 4 4 4 0 5']
['E 5 5 5 5 0']]

如何在此矩阵中找到最小值以及该最小值的索引,在考虑最小值时,排除所有零?

How do I find the minimum in this matrix along with the index of this minimum, excluding all of the zeros when considering the minimum?

我尝试了几种在网上看到的方法,但几乎总是会收到以下错误:TypeError: cannot perform reduce with flexible type

I tried several methods I saw online, but I would almost always get the following error: TypeError: cannot perform reduce with flexible type


我希望尝试使用任何新的解决方案并检查其是否有效?


I would appreciate any new solutions that I can try and check if it works?

推荐答案

您需要使用"numpy"矩阵返回绘图板,该矩阵不是矩阵,而是(单个)字符串列表的列表.

You need to go back to the drawing board with your 'numpy' matrix, that is not an matrix, but a list of list of (single) string.

x =['- A B C D E',
'A 0 2 3 4 5',
'B 2 0 3 4 5',
'C 3 3 0 4 5',
'D 4 4 4 0 5',
'E 5 5 5 5 0']

# Preprocess this matrix to make it a matrix
x = [e.split() for e in x]
numbers = set("0123456789")
xr = [[float(e) if all(c in numbers for c in e) and e != "0" else float("inf") for e in l] for l in x]

所有非数字或0的内容都标记为float(inf),以免影响最小值计算:

Everything that's not a number or 0 is marked as float(inf) to not get into the way of minimum calculation:

[[inf, inf, inf, inf, inf, inf],
 [inf, inf, 2.0, 3.0, 4.0, 5.0],
 [inf, 2.0, inf, 3.0, 4.0, 5.0],
 [inf, 3.0, 3.0, inf, 4.0, 5.0],
 [inf, 4.0, 4.0, 4.0, inf, 5.0],
 [inf, 5.0, 5.0, 5.0, 5.0, inf]]

然后,您可以轻松地使用numpy的argminunravel_index来获取所需的内容.

You can then easily use numpy's argmin and unravel_index to get what you want.

xrn = np.array(xr)
index = np.unravel_index(np.argmin(xrn), xrn.shape)

# RESULT: (1, 2)

这篇关于如何找到一个numpy矩阵的最小值? (在这种情况下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆