Search code examples
pythonnumpymatrixmultidimensional-arrayunique

Count how many unique values there are in each row of a matrix (2d array) in Python


I have a 2d array and I would like find how many unique values there is in each row. For example:

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

Then the output that I desire to obtain would be:

res = np.array([2,1,2,3])

Because there are two uniques values in first row, one unique value in second row, two in third row and three in fourth row.

How can I achieve this? Using np.unique and np.bincounts I was not able.


Solution

  • You can calculate the length of a set for each row.

    [len(set(x)) for x in arr]