如何找到一个numpy矩阵的最小值? (在这种情况下)

编程入门 行业动态 更新时间:2024-10-11 23:24:50
本文介绍了如何找到一个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的argmin和unravel_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矩阵的最小值? (在这种情况下)

本文发布于:2023-11-29 09:46:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646047.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   在这种情况下   最小值   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!