2016-08-22 21 views
5

我想要計算分裂一個大矩陣後遇到的相等矩陣的個數。numpy - count數組相等

mat1 = np.zeros((4, 8)) 

split4x4 = np.split(mat1, 4) 

現在我想知道有多少等於矩陣是在split4x4,但collections.Counter(split4x4)拋出一個錯誤。有沒有一種內置的方式來做到這一點?

+0

啓發我是一個業餘所以這可能聽起來愚蠢,但np.split()將默認分割在相等的片所指定(爲例如陣列: 4在上面的例子),如果它不能比它拋出一個錯誤。那麼,爲什麼你需要找出這些信息,這不僅僅是4? –

回答

1

這可以在一個完全量化的方式,使用numpy_indexed包來完成(免責聲明:我是它的作者):

import numpy_indexed as npi 
unique_rows, row_counts = npi.count(mat1) 

這應該比使用collections.Counter快是基本。

1

也許最簡單的方法是使用np.unique並平整分割陣列比較他們的元組:

import numpy as np 
# Generate some sample data: 
a = np.random.uniform(size=(8,3)) 
# With repetition: 
a = np.r_[a,a] 
# Split a in 4 arrays 
s = np.asarray(np.split(a, 4)) 
s = [tuple(e.flatten()) for e in s] 
np.unique(s, return_counts=True) 

備註:論證新的np.unique在1.9.0版本return_counts

的其它純numpy的溶液從that post

# Generate some sample data: 
In: a = np.random.uniform(size=(8,3)) 
# With some repetition 
In: a = r_[a,a] 
In: a.shape 
Out: (16,3) 
# Split a in 4 arrays 
In: s = np.asarray(np.split(a, 4)) 
In: print s 
Out: [[[ 0.78284847 0.28883662 0.53369866] 
     [ 0.48249722 0.02922249 0.0355066 ] 
     [ 0.05346797 0.35640319 0.91879326] 
     [ 0.1645498 0.15131476 0.1717498 ]] 

     [[ 0.98696629 0.8102581 0.84696276] 
     [ 0.12612661 0.45144896 0.34802173] 
     [ 0.33667377 0.79371788 0.81511075] 
     [ 0.81892789 0.41917167 0.81450135]] 

     [[ 0.78284847 0.28883662 0.53369866] 
     [ 0.48249722 0.02922249 0.0355066 ] 
     [ 0.05346797 0.35640319 0.91879326] 
     [ 0.1645498 0.15131476 0.1717498 ]] 

     [[ 0.98696629 0.8102581 0.84696276] 
     [ 0.12612661 0.45144896 0.34802173] 
     [ 0.33667377 0.79371788 0.81511075] 
     [ 0.81892789 0.41917167 0.81450135]]] 
In: s.shape 
Out: (4, 4, 3) 
# Flatten the array: 
In: s = asarray([e.flatten() for e in s]) 
In: s.shape 
Out: (4, 12) 
# Sort the rows using lexsort: 
In: idx = np.lexsort(s.T) 
In: s_sorted = s[idx] 
# Create a mask to get unique rows 
In: row_mask = np.append([True],np.any(np.diff(s_sorted,axis=0),1)) 
# Get unique rows: 
In: out = s_sorted[row_mask] 
# and count: 
In: for e in out: 
     count = (e == s).all(axis=1).sum() 
     print e.reshape(4,3), count 
Out:[[ 0.78284847 0.28883662 0.53369866] 
    [ 0.48249722 0.02922249 0.0355066 ] 
    [ 0.05346797 0.35640319 0.91879326] 
    [ 0.1645498 0.15131476 0.1717498 ]] 2 
    [[ 0.98696629 0.8102581 0.84696276] 
    [ 0.12612661 0.45144896 0.34802173] 
    [ 0.33667377 0.79371788 0.81511075] 
    [ 0.81892789 0.41917167 0.81450135]] 2 
+0

你在第一個例子中使用python 3嗎?因爲我從'a = r_ [a,a]'得到' 'NameError:名稱'r_'沒有被定義' – andandandand

+0

@andandandand不,我不知道。這是我的錯,我在'r_'之前忘記了'np',這是一種快速構建數組的簡單方法(參見:http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_的.html)。我剛剛糾正了我的答案。 – bougui