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

Find most common value in numpy 2d array rows, otherwise return maximum

I have an array like this

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

I want to return an array with only one column. The condition is to return the most common value in each row; if multiple values have the same number of occurrences, just return the maximum of them.

I used this code

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

most_f = np.array([np.bincount(row).argmax() for row in Nbank])

if multiple values have the same number of occurrences, it returns the first item instead of the maximum. how can I work this around?

>Solution :

I believe this will solve the problem. You could probable make it into a one liner with some fancy list comprehension, but I don’t think that would be worth while.

most_f = []
for n in Nbank: #iterate over elements
    counts = np.bincount(n) #count the number of elements of each value
    most_f.append(np.argwhere(counts == np.max(counts))[-1][0]) #append the last and highest
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