Skip to content

ENH: Create a nlargest and nsmallest methods for pandas.core.groupby.DataFrameGroupBy objects #23993

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

Closed
mcarbajo opened this issue Nov 29, 2018 · 2 comments
Labels
Groupby Needs Info Clarification about behavior needed to assess issue

Comments

@mcarbajo
Copy link

Code Sample, a copy-pastable example if possible

Current method

import pandas as pd

dataframe = pd.DataFrame({'col1': list('aaabbbcc'), 'col2': range(8), 'col3': list('whatever')})
dataframe.groupby('col1').apply(lambda df: df.nlargest(2, 'col2'))

Desired method

import pandas as pd

dataframe = pd.DataFrame({'col1': list('aaabbbcc'), 'col2': range(8), 'col3': list('whatever')})
dataframe.groupby('col1').nlargest(2, 'col2')

Problem description

I want to select the first 2 entries of each group ordered by a specific column. I can easily get these values if I only want to keep the column used for the ordering (see code below) but it gets way less efficient and not as clear when I want to keep all the columns of the DataFrame.

import pandas as pd

dataframe = pd.DataFrame({'col1': list('aaabbbcc'), 'col2': range(8), 'col3': list('whatever')})
dataframe.groupby('col1').col2.nlargest(2)
@mcarbajo mcarbajo changed the title ENH: Create a nlargest and nsmallest methods for pandas.core.groupby.DataFrame objects ENH: Create a nlargest and nsmallest methods for pandas.core.groupby.DataFrameGroupBy objects Nov 29, 2018
@WillAyd
Copy link
Member

WillAyd commented Dec 11, 2018

Might be overlooking it but what is wrong with using apply? We have very few groupby functions outside of apply that either don't maintain the shape of the caller or reduce to a scalar per group, so this would be somewhat of an anomaly. As such -1 as I don't see the value add against using apply

@WillAyd WillAyd added Groupby Needs Info Clarification about behavior needed to assess issue labels Dec 11, 2018
@mroeschke
Copy link
Member

I'm also -1 for the same reason as Will. Since this issue hasn't gotten much traction, closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Groupby Needs Info Clarification about behavior needed to assess issue
Projects
None yet
Development

No branches or pull requests

3 participants