[英]how do I find the index of row in an array that the first column has a specific value and the second column has the max value?
假設我有一個大小為(n,2)
的數組a
,如下所示:
a = np.array([
[6, 185.153],
[6, 9.50864],
[1, 9.31425],
[1, 16.4629],
[6, 19.6971],
[1, 2.02113],
[1, 14.0193],
[5, 2.92495],
[3, 56.0731],
[3, 77.6965],
])
現在我需要找到第一列是特定值M
(例如3)的行的索引,第二個對應列在其他行之間具有最大值,第一列等於M
。 例如,在上面的數組中,索引為8
我使用了以下代碼,但它不起作用並且輸出錯誤。 你知道是什么問題嗎?
indx_nonremoved=np.where([minimum_merge.max(axis=1) ==3 ])[1]
您需要使用列表推導和max()
內置函數的key
參數:
a=[[6, 185.153],
[6, 9.50864],
[1 , 9.31425],
[1 , 16.4629],
[6 ,19.6971],
[1 ,2.02113],
[1 ,14.0193],
[5 ,2.92495],
[3 ,56.0731],
[3 ,77.6965]]
print(a.index(max([i for i in a if i[0]==3], key=lambda x : x[1])))
print(numpy.where(a == max([i for i in a if i[0]==3], key=lambda x : x[1]))) #Use this if a is a numpy.ndarray
輸出:
9
列表推導式當然是一種方法。 如果您已經使用 numpy,並且您有很多數據,那么numpy
方法會更快......
argsort
,從第二列中獲取值# a = np.asarray(a)
mask = (a[:,0] == 3)
# array([False, False, False, False, False, False, False, False, True, True])
(indices,) = np.nonzero(mask)
# array([8, 9], dtype=int64)
maxindex = np.argmax(a[mask, 1])
# 1
indices[maxindex]
# 9
所以第 9 行是最符合您標准的。
您可以以任何方式重新排序a
的行,這仍然是正確的。
同樣可以使用np.argsort
對所有行進行排序,而不是僅獲取最大值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.