Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading