1

By the following program, I am trying to calculate the number of occurance of '0','1','2',and '3' for each column. The program is not working as desired. I read somewhere that slicing of the matrix should be done for computing the occurance column wise but I am not sure how to do it. The program is written using numpy in python. How to do it using 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)`

Also I want to print it in the following manner:

    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

2 Answers 2

0

Here is the code using list functionality

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

Output:

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}
Sign up to request clarification or add additional context in comments.

Comments

0

This should give you the output format you want:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.