我有一個二維陣列,我正在嘗試獲取第二個軸上最大數字的索引和值。例如:
[
[1, 5, 3],
[6, 2, 4],
[4, 3, 5]
]
將回傳[indexofmax, max]每一行。
所以:
[
[1, 5],
[0, 6],
[2, 5]
]
uj5u.com熱心網友回復:
這條線理解應該這樣做:
def get_max_index(arr):
return [[subarr.index(max(subarr)), max(subarr)] for subarr in arr]
注意 - 這只會回傳最大數字的第一個索引。
uj5u.com熱心網友回復:
由于您標記了numpy,請嘗試使用argmax和take_along axis:
# convert to numppy array if not already is
arr = np.array(arr)
idx = np.argmax(arr, axis=1)[..., None] # the index of row maxmimum
np.hstack([idx, np.take_along_axis(arr, idx, axis=1)])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322016.html
