Reputation: 57
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.
Upvotes: 4
Views: 556
Reputation: 30070
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
Upvotes: 4