雖然numpy數組中有argmax的函數可以獲得數組的最大值的索引,但該函數獲得的是numpy數組平鋪后的索引,也就是一維索引。那么要怎樣才能獲得二維索引呢?實現很簡單,比如我下面的代碼:
import numpy as np import math a = np.array([[1, 2, 3], [4, 5, 6]]) m, n = a.shape index = int(a.argmax()) x = int(index / n) y = index % n print(x, y) >>>1 2
雖然math和numpy都有取整的方法,math.ceil向上取整,math.floor向下取整,math.round四舍五入取整。但獲得的結果是float型。所以這里使用int()向下取整獲得int型結果。
雖然我們實現了二維索引的獲取,但是如果是三維呢?
import numpy as np import math a = np.array([[[1, 2, 3], [4, 5, 6]]]) m, n, l = a.shape index = int(a.argmax()) x = int(index / (n*l)) index = index % (n*l) y = int(index/l) index = index % l z = index print(x, y, z) >>>0 1 2
很好理解,但是很繁瑣,這里有一種簡單的方法利用np.unravel_index()獲取索引。
至於np.unravel_index函數https://blog.csdn.net/dn_mug/article/details/70256109說的比較清楚。
對於二維數組:
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) index = np.unravel_index(a.argmax(), a.shape) print(index) >>>(1, 2)
三維數組:
import numpy as np a = np.array([[[1, 2, 3], [4, 5, 6]]]) index = np.unravel_index(a.argmax(), a.shape) print(index) >>>(0, 1, 2)
一句話搞定,獲得二維或多維數組最值的索引。