簡體   English   中英

計算numpy 2D數組中的出現次數

[英]Counting number of occurrences in numpy 2D array

我有一個二維 numpy 數組,如下所示:

import numpy as np

a=np.array([[1,2],[1,1], [2,1],[2,2],[3,2],[3,2], [3,1], [4,2],[4,1]])
print(a)

我需要為第 1 列中的每個值計算第 2 列中出現多少個 1 或 2 的值。例如,當第 1 列中的 x=3 時,第 2 列中有兩個值 2 的實例和一個值 1 的實例.

任何有關如何完成此操作的指示將不勝感激! 我想我可以用 np.unique 做某種 for 循環,但我不確定......

正如您的評論一樣,如果您想要列表格式,請嘗試以下操作:

out = [[k, *np.unique(a[a[:,0] == k,1], return_counts=True)[1]] 
                                              for k in np.unique(a[:,0])]

Out[838]: [[1, 1, 1], [2, 1, 1], [3, 1, 2], [4, 1, 1]]

對於二維陣列

out = np.array([[k, *np.unique(a[a[:,0] == k,1], return_counts=True)[1]] 
                                                 for k in np.unique(a[:,0])])

Out[850]:
array([[1, 1, 1],
       [2, 1, 1],
       [3, 1, 2],
       [4, 1, 1]], dtype=int64)

一個簡單的方法是使用帶有collections.Counternp.unique字典理解

from collections import Counter

out = {k: Counter(a[a[:,0] == k,1]) for k in np.unique(a[:,0])}

Out[821]:
{1: Counter({2: 1, 1: 1}),
 2: Counter({1: 1, 2: 1}),
 3: Counter({2: 2, 1: 1}),
 4: Counter({2: 1, 1: 1})}

假設您在第一列中的值從 1 到N ,在第二列中從 1 到M ,這是一種非常簡單且快速的方法:

import numpy as np

a = np.array([[1, 2], [1, 1], [2, 1], [2, 2], [3, 2], [3, 2], [3, 1], [4, 2], [4, 1]])
c = np.zeros(a.max(0), np.int32)
np.add.at(c, tuple(a.T - 1), 1)
# c[i, j] contains the number of times
# the second column value is j + 1 when
# the first column value is i + 1

# Print result
for i in range(c.shape[0]):
    print(f'Count result for {i + 1}')
    for j in range(c.shape[1]):
        print(f'    Number of {j + 1}s: {c[i, j]}')

輸出:

Count result for 1
    Number of 1s: 1
    Number of 2s: 1
Count result for 2
    Number of 1s: 1
    Number of 2s: 1
Count result for 3
    Number of 1s: 1
    Number of 2s: 2
Count result for 4
    Number of 1s: 1
    Number of 2s: 1

這通過使陣列簡單地工作c零,然后基本上增加一個到每行/列c指示由每行a 從概念上講,它等價於c[a[:, 0] - 1, a[:, 1] - 1] += 1 但是,這樣做可能不起作用,因為a包含重復的行,因此 NumPy 最終只計算其中的一個。 要正確執行此操作,您需要使用np.addat方法(此方法在其他 ufunc 中也可用,請參閱通用函數 (ufuncs) )。 這會在每個位置添加給定值( tuple(aT - 1)一個帶有行索引和列索引的元組),正確計算重復位置。

您可以使用條件過濾 np 數組,然后使用unique方法來獲取計數

嘗試以下解決方案:

import numpy as np

a = np.array(
    [[1, 2], [1, 1], [2, 1], [2, 2], [3, 2], [3, 2], [3, 1], [4, 2], [4, 1]])

b = a[np.any(a == 3, axis=1)]

print(len(b[np.any(b == 2, axis=1)])) #output: 2
print(len(b[np.any(b == 1, axis=1)])) #output: 1

unique, counts = np.unique(b, return_counts=True)

print(dict(zip(unique, counts))) #output: {1: 1, 2: 2, 3: 3}

簡短的解決方案:

unique, counts = np.unique(a[np.any(a == 3, axis=1)], return_counts=True) #replace 3 with x

print(dict(zip(unique, counts)))

輸出:

{1: 1, 2: 2, 3: 3}

暫無
暫無

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

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