Search code examples
pythonpython-3.xpandaslistcounter

List elements’ counter


New to Python here.

I am looking for a simple way of creating a list (Output), which returns the count of the elements of another objective list (MyList) while preserving the indexing(?).

This is what I would like to get:

MyList = ["a", "b", "c", "c", "a", "c"]
Output = [ 2 ,  1 ,  3 ,  3 ,  2 ,  3 ]

I found solutions to a similar problem. Count the number of occurrences for each element in a list.

In  : Counter(MyList)
Out : Counter({'a': 2, 'b': 1, 'c': 3})

This, however, returns a Counter object which doesn't preserve the indexing.

I assume that given the keys in the Counter I could construct my desired output, however I am not sure how to proceed.

Extra info, I have pandas imported in my script and MyList is actually a column in a pandas dataframe.


Solution

  • Instead of listcomp as in another solution you can use the function itemgetter:

    from collections import Counter
    from operator import itemgetter
    
    lst = ["a", "b", "c", "c", "a", "c"]
    
    c = Counter(lst)
    itemgetter(*lst)(c)
    # (2, 1, 3, 3, 2, 3)
    

    UPDATE: As @ALollz mentioned in the comments this solution seems to be the fastet one. If OP needs a list instead of a tuple the result must be converted wih list.