How Do I Find The Minimum Of A Numpy Matrix? (In This Particular Case)
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
Solution 1:
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]
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]]
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)
Post a Comment for "How Do I Find The Minimum Of A Numpy Matrix? (In This Particular Case)"