如何从python矩阵的每一列中选择具有最多最小值的行?

时间:2019-06-22 09:27:55

标签: python numpy

假设我有一个名为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做到这一点?

2 个答案:

答案 0 :(得分:2)

肯定有更清洁的解决方案,但这可行:

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

答案 1 :(得分:2)

对于每个子列表固定数量的元素,我们可以像这样使用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]
相关问题