learner
learner

Reputation: 877

How to calculate count of occurence of each value from a list column of Pandas efficiently?

I have a Pandas data frame, which looks like the following:

      df =
                  col1

                  ['a', 'b']
                  ['d', 'c', 'a']
                  ['b', 'f', 'a']

col1 is a list column, which contains strings. I want to calculate value counts of each element, which may occur in any of the lists in any row. Expected output is a dictionary, of counts of each value

Expected Output

      df_dict = {'a': 3, 'b': 2, 'c': 1, 'd': 1, 'f': 1}

How to do this efficiently in 1 line preferably to make the code clean. Sorry, if it has been answered before.

Upvotes: 0

Views: 38

Answers (1)

perl
perl

Reputation: 9941

With explode and value_counts:

df['col1'].explode().value_counts().to_dict()

Output:

{'a': 3, 'b': 2, 'd': 1, 'f': 1, 'c': 1}

Upvotes: 3

Related Questions