簡體   English   中英

如何從python矩陣的每一列中選擇具有最多最小值的行?

[英]How do I select a row with most number of minimum values out of each column from a matrix in python?

假設我有一個名為arr的2D列表

arr=[[0.2, 0.4, 0.5, 0.3],[0.4, 0.3, 0.6, 0.7],[0.3, 0.5, 0.9, 0.4]]

現在,我想返回與最小值相比最多的一行最小值,在這種情況下為arr [0]。

[0.2, 0.4, 0.5, 0.3]

如何使用純python或numpy做到這一點?

肯定有更清潔的解決方案,但這可行:

arr=[[0.2, 0.4, 0.5, 0.3],[0.4, 0.3, 0.6, 0.7],[0.3, 0.5, 0.9, 0.4]]

#list of min count of each array 
counts=[0] * len(arr)
#iterate over all values
for i in range (len(arr[0])):
  minwhere=0 #position min value
  val=arr[0][i] #current min value
  for j in range (1, len(arr)): #iterate over other arrays
    if val > arr[j][i]: #compare for min
      minwhere=j #update index array min
      val=arr[j][i] #update value min
  counts[minwhere]=counts[minwhere]+1 #add one to array with min


print (arr[counts.index(max(counts))]) #get arr with max number of min

對於每個子列表固定數量的元素,我們可以像這樣使用NumPy:

In [53]: arr[np.bincount(np.argmin(arr,axis=0)).argmax()]
Out[53]: [0.2, 0.4, 0.5, 0.3]

另外,我們也可以使用SciPy來獲得最多的計數步驟,如下所示-

In [45]: from scipy import stats

In [46]: arr[stats.mode(np.argmin(arr,axis=0))[0][0]]
Out[46]: [0.2, 0.4, 0.5, 0.3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM