HimanUCC HimanUCC - 4 months ago 11
Python Question

Add the count value of occurrences of different values in a table as a new column to the table using pandas

In the following table, how can I count the number of occurrences of different User IDs and make a new table that has the User IDs and the count values only.

enter image description here

For example, I want a new table that looks like this:

User count
5173 3
5175 2
5181 1
5183 2

Answer

you can use value_counts() method:

df.User.value_counts().to_frame('count').reset_index().rename(columns=dict(index='User'))

or if you want to keep User column as an index:

df.User.value_counts().to_frame('count')