2015-07-19 34 views
3

例如,如果我有:如何計算元素的矢量的NUM與numpy的蟒蛇

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

我們可以看到,我們有數字1的四倍,4號兩次,3只的。

我想有以下結果:

array(4,4,2,4,2,1,4) 

正如你可以看到:每個單元由計數的它的元素所取代。

我該如何以最有效的方式做到這一點?

+0

[numpy:數組中唯一值的頻率計數]的可能重複(http://stackoverflow.com/questions/10741346/numpy-frequency-counts-for-unique-values-in-an-array) –

回答

3

一個vectorized方法與np.uniquenp.searchsorted -

# Get unique elements and their counts 
unq,counts = np.unique(a,return_counts=True) 

# Get the positions of unique elements in a. 
# Use those positions to index into counts array for final output. 
out = counts[np.searchsorted(unq,a.ravel())] 

採樣運行 -

In [86]: a 
Out[86]: array([[1, 1, 4, 1, 4, 3, 1]]) 

In [87]: out 
Out[87]: array([4, 4, 2, 4, 2, 1, 4]) 

按照從@Jaime的評論,你可以使用np.unique單獨像這樣 -

_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True) 
out = counts[inv_idx] 
+0

您可以從'unique'獲得與'_,inv,cnt = np.unique(a,return_inverse = True,return_counts = True)'相同的結果',然後'cnt [inv]'會給你OP後面的內容。 – Jaime

+0

@Jaime將這些添加爲編輯。感謝您的意見! – Divakar

0

使用collections.Counter

from collections import Counter 
ctr = Counter(a.flat) 
result = np.array([ctr[i] for i in a.flat]) 

如果你希望你的result具有相同的尺寸a,使用reshape

result = result.reshape(a.shape) 
0

我試圖既numpy的和計數器相結合:

from collections import Counter 
a=np.array([[1,1,4,1,4,3,1]]) 

# First I count the occurence of every element and stor eit in the dict-like counter 
# Then I take its get-method and vectorize it for numpy-array usage 
vectorized_counter = np.vectorize(Counter(a.flatten()).get) 

vectorized_counter(a) 

出:

array([[4, 4, 2, 4, 2, 1, 4]])