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
.
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
.
Setup
As of v0.23, there are a multiple possible options to use.
ngroups
Newer versions of the groupby API provide this (undocumented) attribute which stores the number of groups in a GroupBy object.
len
You can either call
len
on theGroupBy
object directly, or on theGroupBy.groups
attribute. This delegates toGroupBy.__len__
to retrieve the number of groups.Generator Expression
For completeness, you can also iterate over groups.
If you wanted to actually print those groups out, you could do something like
Addendum
If you're looking to find the size of each group, you can use
DataFrameGroupBy.size
:Note that
size
counts NaNs as well. If you don't want NaNs counted, useg.count()
instead.And lastly, there's also the option of
value_counts
throughdf.groupby('A').B.value_counts()
which gives the exact same result asg.count()
but does the grouping on one column instead of two.As documented, you can get the number of groups with
len(dfgroup)
.