Reputation: 357
I have a table like this:
Actor1 Actor2 Actor3
0 Bob Alice Tom
1 Frank Bob Sam
I want to count the number of times each actor occurs anywhere. In other words, Bob = 2, while the others are 1.
I know how to count per column and add, and I know I can merge each column into a very long Series. But there must be a better way?
Upvotes: 1
Views: 130
Reputation: 10590
You could use np.unique
and set return_counts=True
. This will return two lists with the unique values and counts.
np.unique(df, return_counts=True)
Output:
(array(['Alice', 'Bob', 'Frank', 'Sam', 'Tom'], dtype=object),
array([1, 2, 1, 1, 1], dtype=int64))
Otherwise you can use df.stack().value_counts()
to which you (and @ShubhamSharma!) allude.
Upvotes: 3