Get Number of Cases by Group in pandas DataFrame in Python (Example Code)

On this page you’ll learn how to count the number of cases by group in a pandas DataFrame in the Python programming language.

Setting up the Example

import pandas as pd                         # Import pandas library in Python
my_df = pd.DataFrame({'A':range(19, 28),    # Constructing a pandas DataFrame
                      'B':[6, 7, 3, 9, 1, 3, 8, 8, 9],
                      'C':range(20, 11, - 1),
                      'GRP_a':['gr1', 'gr1', 'gr2', 'gr3', 'gr1', 'gr2', 'gr2', 'gr3', 'gr3']})
print(my_df)
#     A  B   C GRP_a
# 0  19  6  20   gr1
# 1  20  7  19   gr1
# 2  21  3  18   gr2
# 3  22  9  17   gr3
# 4  23  1  16   gr1
# 5  24  3  15   gr2
# 6  25  8  14   gr2
# 7  26  8  13   gr3
# 8  27  9  12   gr3

Example: Number of Rows by Group in pandas DataFrame

print(my_df.groupby('GRP_a').size())        # Count rows by group column
# GRP_a
# gr1    3
# gr2    3
# gr3    3
# dtype: int64

Further Resources & Related Articles

Here, you can find some further resources on topics such as groups, counting, and dates:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top