簡體   English   中英

在 2d numpy 數組的行中查找唯一數組組合的模式

[英]Finding mode of unique array combination in the rows of 2d numpy array

我有一個 2d numpy 數組,我試圖沿axis = 0 (行)返回模式數組。 但是,我想返回最頻繁的唯一行組合。 而不是所有三列的三種模式,這是 scipy 統計模式所做的。 下面示例中所需的 output 將是[9,9,9] ,因為這是最常見的唯一行。 謝謝

from scipy import stats

arr1 = np.array([[2,3,4],[2,1,5],[1,2,3],[2,4,4],[2,8,2],[2,3,1],[9,9,9],[9,9,9]])

stats.mode(arr1, axis = 0)

output:

ModeResult(mode=array([[2, 3, 4]]), count=array([[5, 2, 2]]))

您可以使用 numpy 獨特的功能和返回計數。

unique_arr1, count = np.unique(arr1,axis=0, return_counts=True)
unique_arr1[np.argmax(count)]

output:

array([9, 9, 9])

np.unique 以排序順序返回唯一數組,這意味着保證最后一個是最大值。 你可以簡單地做:

out = np.unique(arr1,axis=0)[-1]

但是,我不知道您要出於什么目的使用它,只是想提一下,您可以擁有所有計數,以防萬一您想要驗證或考慮具有相同計數的多行。

更新給出的附加信息,這是針對圖像(可能很大),最重要的是,第二個暗淡可以適合 int(每個值是 uin8 或 16)可以適合 int32 或 64。(考慮 uint8 中每個像素的值):

pixel, count = np.unique(np.dot(arr, np.array([2**16,2**8,1])),  return_counts=True)
pixel = pixel[np.argmax(count)]
b,g, r, = np.ndarray((3,), buffer=pixel, dtype=np.uint8)

這可能會導致很大的加速。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM