Computer >> Computer tutorials >  >> Programming >> Python

Count unique values per groups in Python Pandas


To count unique values per groups in Python Pandas, we can use df.groupby('column_name').count().

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Use df.groupby('rank')['id'].count() to find the count of unique values per groups and store it in a variable "count".
  • Print the count from Step 3.

Example

import pandas as pd

df = pd.DataFrame(
    {
       "id": [1, 2, 1, 3, 5, 1, 4, 3, 6, 7],
       'rank': [1, 4, 1, 2, 1, 4, 6, 1, 5, 3]
    }
)

print"Input DataFrame 1 is:\n", df
count = df.groupby('rank')['id'].count()
print"Frequency of ranks:\n", count

Output

Input DataFrame 1 is:

   id  rank
0   1    1
1   2    4
2   1    1
3   3    2
4   5    1
5   1    4
6   4    6
7   3    1 
8   6    5
9   7    3
Frequency of ranks:
rank
1  4
2  1
3  1
4  2
5  1
6  1
Name: id, dtype: int64