Amani
Amani

Reputation: 18123

Frequency of unique values in different columns in pandas

I have a pandas data frame like this:

Index   arrival_1   arrival_2   arrival_3
1        elephant    lion        buffalo
2        buffalo     antelope    hippo
3        lion        buffalo     antelope
4        hippo       lion        antelope
5        elephant    buffalo     lion
6        buffalo     lion        hippo

I need to calculate the frequency of each unique arrival item across all the three columns (arrival_1, arrival_2, arrival_3), e.g. the frequency of elephant across all the three arrival columns is 3, that of lion is 5. How can this be done in pandas?

Expected output looks like this:

Item      count
elephant    2
lion        5
buffalo     5
antelope    3
hippo       3

Upvotes: 2

Views: 1542

Answers (1)

su79eu7k
su79eu7k

Reputation: 7316

Try below.

df.stack().value_counts()

Upvotes: 5

Related Questions