How to get number of groups in a groupby object in pandas?
This would be useful so I know how many unique groups I have to perform calculations on. Thank you. Suppose groupby object is called dfgroup . As documented , you can get the number of groups with len(dfgroup) . As of v0.23, there are a multiple options to use. First, the setup, df = pd.DataFrame({'A': list('aabbcccd'), 'B': 'x'}) df A B 0 a x 1 a x 2 b x 3 b x 4 c x 5 c x 6 c x 7 d x g = df.groupby(['A']) 1) ngroups Newer versions of the groupby API provide this (undocumented) attribute which stores the number of groups in a GroupBy object. g.ngroups # 6 Note that this is different from