Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list first N rows from Pandas df using groupby

I am using the following code to group a pandas df, and pass the values grouped to a list

  df.groupby(['Column1','Column2'])['Column3'].apply(list)

This returns all values from column3 in the list.
How can i get the list to include only first N examples only from column3 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use indexing with lambda function:

df.groupby(['Column1','Column2'])['Column3'].apply(lambda x: list(x)[:N])

Or:

df.groupby(['Column1','Column2'])['Column3'].apply(lambda x: list(x.iloc[:N]))

EDIT:

df.groupby(['Column1','Column2'])['Column3'].apply(lambda x: list(x.unique()[:N]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading