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

Feature Request: Sample method for Groupby objects #31775

Closed
yadunathg opened this issue Feb 7, 2020 · 3 comments · Fixed by #34069
Closed

Feature Request: Sample method for Groupby objects #31775

yadunathg opened this issue Feb 7, 2020 · 3 comments · Fixed by #34069
Assignees
Milestone

Comments

@yadunathg
Copy link

Many times it is desirable to be able to iterate over a small number of groups of a group by object. Currently there is no direct way to get a random sample of groups.

Similar to DataFrame.sample method, can we have Groupby.sample method which gives us a Dictionary{'group_name'->'group_labels'} containing n randomly selected groups?

Expected behaviour

import pandas as pd
df = pd.DataFrame([['Male', 1], ['Female', 3], ['Female', 2], ['Other', 1]],
                                 columns=['gender', 'feature'])
grouped_df = df.groupby('gender')

# Desired feature
grouped_df.sample(n=2)
# {'Female': Int64Index([1, 2], dtype='int64'),
#  'Male': Int64Index([0], dtype='int64')}
@yadunathg yadunathg changed the title Feature Request: Sample for Groupby objects Feature Request: Sample method for Groupby objects Feb 7, 2020
@charlesdong1991
Copy link
Member

interesting, will look into it

@echozzy629
Copy link

take

@yadunathg
Copy link
Author

Thanks for adding the sample feature into groupby. However, behaviour of the added feature is different from what I had requested.

I wanted to get a sample of groups from the groupby objects. But the added feature allows us to get a sample of records from each group of the groupby object. Is it possible to add an argument to the sample method which allows us to choose whether the sampling should be done on the groups or records of each group?

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

Successfully merging a pull request may close this issue.

5 participants