2016-02-07 66 views
1

這裏是在python的數組:計數陣列蟒

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

print np.where(T==1) 

我想找到每個元素的出現次數。我試圖使用np.where,然後len(np.where)。但np.where的輸出不允許使用len()函數。

+0

是這些答案中的任何一個對你的問題有用嗎? – Dalek

回答

0

使用numpy.unique,它返回數組中唯一值和出現次數。該方法有一個稱爲return_counts標誌,它是默認值是false這樣的:

uniqueVals, count = numpy.unique(T, return_counts = true)

+0

'numpy.unique'可以在沒有'reshape'的情況下工作,但是你傳遞了什麼參數來獲取出現次數? – Akavall

+0

@Akavall'return_counts = true' –

+1

啊。太好了!也許你應該在你的答案中包含這一點。 – Akavall

0

可以執行如下顯示的次數,所述元件1的陣列T中被重複:

>>> (T == 1).sum() 
4 
>>> (T == 2).sum() 
2 
0

如果數組中的整數的範圍小,你可以使用np.bincount

In [25]: T = np.array([[1,1,2],[2,1,1],[3,3,3]]) 

In [26]: np.bincount(T.reshape(-1)) 
Out[26]: array([0, 4, 2, 3]) # 0 showed up 0 times 
           # 1 showed up 4 times 
           # 2 showed up 2 times ...