SamR
SamR

Reputation: 77

Find most common object of a list and the locations of its appearances

I would like to find the most common element in a list but in addition I would like to have the location of each appearance. For example, if I have the following array:

array([[[1503,    0]],

       [[6600,    0]],

       [[1503,    0]],

       [[6320,    0]],

       [[1503,    0]]], dtype=int64)

the output I would like to have is something like: 1503, [0, 2, 4] , where the first output (1503) is the most common element of my list and the second output ([0, 2, 4]) is the list of locations.

I have used the following code snippet:

from collections import Counter

def find_majority(accounts):
    accounts_count = Counter(accounts)
    top_account = accounts_count.most_common(1)
    if len(top_account)>1 and top_account[0][1] == top_account[1][1]:
        # It is a tie
        return 0
    return top_account[0][0]

It gives me the most common element but I can't figure out how to upgrade this code snippet in order to find the locations as well.

Upvotes: 1

Views: 184

Answers (2)

gsamaras
gsamaras

Reputation: 73366

Use np.where like this:

import numpy as np
from collections import Counter

accounts = np.array([1503, 6600, 1503, 6320, 1503])

def find_majority(accounts):
    accounts_count = Counter(accounts)
    top_account = accounts_count.most_common(1)
    if len(top_account)>1 and top_account[0][1] == top_account[1][1]:
        # It is a tie
        return None, None
    return top_account[0][0], np.where(accounts == top_account[0][0])[0]
    
print(find_majority(accounts))

Output:

(1503, array([0, 2, 4]))

Read more in Find the most common element in a list.

Upvotes: 2

marecmat
marecmat

Reputation: 21

Since you have the value you're looking for, you can use np.where which takes a condition as an input. If say your most common element is 1503, np.where(array == 1503) returns an array of the same shape with True where you have the location.

Upvotes: 0

Related Questions