我有一个如下的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矩阵的最小值? (在这种情况下)
发布评论