0

i am finding counts of unique values row-wise

import numpy as np np.random.seed(100) arr = np.random.randint(1,11,size=(6, 10)) arr

    output::
    array([[ 9,  9,  4,  8,  8,  1,  5,  3,  6,  3],
           [ 3,  3,  2,  1,  9,  5,  1, 10,  7,  3],
           [ 5,  2,  6,  4,  5,  5,  4,  8,  2,  2],
           [ 8,  8,  1,  3, 10, 10,  4,  3,  6,  9],
           [ 2,  1,  8,  7,  3,  1,  9,  3,  6,  2],
           [ 9,  2,  6,  5,  3,  9,  4,  6,  1, 10]]) 

my code to finding counts of unique values row wise

row,col = np.shape(arr) 
for i in range(row):
    a,c = np.unique(arr[i], return_counts = True)
    print(c)

output::
[1 2 1 1 1 2 2]
[2 1 3 1 1 1 1]
[3 2 3 1 1]
[1 2 1 1 2 1 2]
[2 2 2 1 1 1 1]
[1 1 1 1 1 2 2 1]

But i want my output to look like this

[[1, 0, 2, 1, 1, 1, 0, 2, 2, 0],
 [2, 1, 3, 0, 1, 0, 1, 0, 1, 1],
 [0, 3, 0, 2, 3, 1, 0, 1, 0, 0],
 [1, 0, 2, 1, 0, 1, 0, 2, 1, 2],
 [2, 2, 2, 0, 0, 1, 1, 1, 1, 0],
 [1, 1, 1, 1, 1, 2, 0, 0, 2, 1]]  

1 Answers1

2

I think what you want is np.bincount:

row,col = np.shape(arr) 
for i in range(row):
    c = np.bincount(arr[i], minlength=11)[1:] #The purpose of [1:] is to ignore the first element
    print(c)

this gives you a bunch of 1D arrays, not the 2D array you wanted. However, have a look at, for example, this question Can numpy bincount work with 2D arrays?.

cheetah
  • 201
  • 1
  • 5