如何通過numpy獲得二維或多維數組的最大、小值索引


雖然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)

一句話搞定,獲得二維或多維數組最值的索引。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM