Pandas - count distinct values per column

Viewed 1329

I have a dataframe that looks like this:

Id ActivityId ActivityCode

1   2           3
1   2           4
1   3           2

I need to get a count of the distinct Activity IDs that the Id is related to.

In the example above, id 1 would return 2 since there're 2 distinct activity ids for that id.

The SQL would look this way:

SELECT COUNT(DISTINCT ActivityId) FROM table GROUP BY Id

How do I do this in pandas?

(And if possible, I'd like to know if there's a way to get the result in a dictionary, without iterating manually)

1 Answers
Related