2017-03-28 26 views
1

通过以下程序,我试图计算每列出现'0','1','2'和'3'的次数。该程序没有按照要求工作。我在某处读到矩阵切片应该用于计算发生列的明智之处,但我不知道如何去做。该程序使用Python中的numpy编写。如何使用numpy做到这一点?在Python中使用numpy计算列的明智性

import numpy as np 
a=np.array([[ 2,1,1,2,1,1,2], #t1 is horizontal 
[1,1,2,2,1,1,1], 
[2,1,1,1,1,2,1], 
[3,3,3,2,3,3,3], 
[3,3,2,3,3,3,2], 
[3,3,3,2,2,2,3], 
[3,2,2,1,1,1,0]]) 
print(a) 
i=0 
j=0 
two=0 
zero=0 
one=0 
three=0 
r=a.shape[0] 
c=a.shape[1] 

for i in range(1,r): 
#print(repr(a)) 
for j in range(1,c): 
    #sele=a[i,j] 
    if (a[i,j]==0): 
     zero+=1 
    if (a[i,j]==1): 
     one+=1 
    if (a[i,j]==2): 
     two+=1 
    if (a[i,j]==3): 
     three+=1 
    if i==c-1: 
     #print(zero) 
     print(one) 
     i+=0 
     j=j+1 
     #print(two) 
     #print(three) 
    i=i+1 
    #print(zero)` 

此外,我想打印以下方式:

column:   0 1 2 3 4 5 6 
    occurrences: 0 0 0 0 0 0 0 1 
        1 1 3 2 2 4 3 1 
        2 2 1 3 4 1 2 2 
        3 4 3 2 1 2 2 2 

回答

0

下面是使用列表功能的代码

import numpy as np 
inputArr=np.array([[ 2,1,1,2,1,1,2], 
       [1,1,2,2,1,1,1], 
       [2,1,1,1,1,2,1], 
       [3,3,3,2,3,3,3], 
       [3,3,2,3,3,3,2], 
       [3,3,3,2,2,2,3], 
       [3,2,2,1,1,1,0] 
       ]) 

occurance = dict() 
toFindList = [0,1,2,3] 
for col in range(len(inputArr)): 
    collist = inputArr[:, col] 
    collist = (list(collist)) 
    occurance['col_' + str(col)] = {} 
    for num in toFindList: 
     occurcount = collist.count(num) 
     occurance['col_' + str(col)][str(num)] = occurcount 

for key, value in occurance.iteritems(): 
    print key, value 

输出:

col_2 {'1': 2, '0': 0, '3': 2, '2': 3} 
col_3 {'1': 2, '0': 0, '3': 1, '2': 4} 
col_0 {'1': 1, '0': 0, '3': 4, '2': 2} 
col_1 {'1': 3, '0': 0, '3': 3, '2': 1} 
col_6 {'1': 2, '0': 1, '3': 2, '2': 2} 
col_4 {'1': 4, '0': 0, '3': 2, '2': 1} 
col_5 {'1': 3, '0': 0, '3': 2, '2': 2} 
0

这应该给你你想要的输出格式:

def col_unique(a): 
    return np.sum(np.dstack([np.in1d(a,i).reshape(a.shape) for i in np.unique(a)]), axis = 0).T