Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the occurrence of each value in a Pandas column in a separate list

I have a Pandas dataframe column with unique values:

  c1
1 a
2 b
3 c

I want to count the occurrences of these values in two separate lists, and append the counts to the dataframe. The separate list might look like:

my_list1 = [a,b,a,c,c,a,b,a]
my_list2 = [b,c,c,a,a,b,c,a]

So the final result would be a pandas dataframe similar to this:

   c1 c2 c3
1  a  4  3
2  b  2  2
3  c  2  3

I could make the list into a dictionary and create a dataframe from that dictionary, but this is complicated by needing to do this for two lists. I tried to make a dictionary of the two dictionaries, but could not get it into a dataframe.

like image 999
ccs Avatar asked Mar 01 '23 15:03

ccs


1 Answers

Use collections.Counter()

from collections import Counter

df['c2'] = df['c1'].map(Counter(my_list1))
df['c3'] = df['c1'].map(Counter(my_list2))
# print(df)

  c1  c2  c3
0  a   4   3
1  b   2   2
2  c   2   3
like image 199
Ynjxsjmh Avatar answered Mar 05 '23 17:03

Ynjxsjmh