Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement GroupBy __len__ to return number of resulting groups #95

Closed
bburan opened this issue Aug 9, 2011 · 0 comments
Closed

Implement GroupBy __len__ to return number of resulting groups #95

bburan opened this issue Aug 9, 2011 · 0 comments

Comments

@bburan
Copy link

bburan commented Aug 9, 2011

Right now there is no way (to my knowledge) to get the number of groups that the DataFrame.groupby() method creates. For example (using Pandas 0.4 dev):

from pandas import *; from numpy.random import randn
data = { 'A': rand(4), 'B': rand(4), 'C': (0, 1, 1, 1)}
df = DataFrame(data)
grouping = df.groupby('C')
len(grouping)

TypeError: object of 'DataFrameGroupBy' has no len()

This seems counter intuitive considering iter is implemented. Having the len() method would be very useful if we need to know the number of existing groups prior to iterating through the groups (e.g.. one use case would be to determine the number and layout of subplots, one for each group, in a Matplotlib figure).

Right now, I typically just do:

grouping = list(df.groupby('C'))
n = len(grouping)
# do something with n

for key, frame in grouping:
# do something

(updated to fix formatting)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants