Search code examples
pythonlistnested-lists

How to count the number of times 1s predicted by a classifier for a particular instance


Suppose I have a following lists of list containing labels predicted by a 3 classifier of same type

List = [[0,1,1,0],[1,1,1,0],[0,0,1,1]]

How can I get the following?

List1 =[0,1,1,0]

which are labels that are predicted by most of the classifiers.


Solution

  • zip the lists together and get the most common element from each tuple.

    arr = [[0, 1, 1, 0], [1, 1, 1, 0], [0, 0, 1, 1]]
    [max(set(x), key=x.count) for x in zip(*arr)]
    # [0, 1, 1, 0]
    

    Or, using pandas, convert the list of lists to a DataFrame and get mode along the columns

    import pandas as pd
    
    pd.DataFrame(arr).mode().iloc[0,:].tolist()
    # [0, 1, 1, 0]