對于矩陣,我想獲取每列具有較小值的行(如果存在) - 嚴格由所有其他行主導。例如,
A = [[7,5,8,2]
[10,3,7,8]
[6,2,6,1]]
B = [[7,5,8,2]
[10,3,7,8]
[9,5,6,7]
[6,2,6,1]]
對于矩陣 A,行[6,2,6,1]具有最小值。對于 i 的所有值,A[2][i] < A[1][i] 和 A[2][i] < A[0][i]。所以,它的索引應該被回傳。
對于矩陣 B,不存在具有最低值的行(第 2 列中的 6 不小于該列中的其他值)。
除了單獨回圈每列之外,還有更清潔的方法嗎?
uj5u.com熱心網友回復:
干得好。請參閱注釋了解每行的作用。
import numpy as np
def get_index_of_minimum_row(arr):
""" returns the index of the minimum row or None if it does not exist """
#Get the minimum value of each column.
column_minimums = arr.min(axis=0)
#Create a mask of the array for the minimum values (True where it is the minimum, False where it is not).
column_minimums_mask = arr <= column_minimums
#Ensure that the minimum value is the only minimum value in its column.
has_only_one_minimum_per_column = column_minimums_mask.sum() == arr.shape[1]
if not has_only_one_minimum_per_column:
return None
#Ensure that all minimums are in the same row.
all_minimums_are_in_the_same_row = column_minimums_mask.all(axis=1)
if not all_minimums_are_in_the_same_row.any():
return None
#Get the index of the minimum row and return it
return np.squeeze(np.argwhere(all_minimums_are_in_the_same_row))
A = np.array([
[7,5,8,2],
[10,3,7,8],
[6,2,6,1],
])
B = np.array([
[7,5,8,2],
[10,3,7,8],
[9,5,6,7],
[6,2,6,1],
])
print(get_index_of_minimum_row(A)) #returns 2
print(get_index_of_minimum_row(B)) #returns None
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/519656.html
標籤:Python麻木的
上一篇:y_true和y_pred的向上、向下、相等方向的一致性比
下一篇:兩個陣列之間的Numpy不同元素
