简体   繁体   中英

how can i select only the first two rows for every level (0) in my multiindex pandas dataframe?

say i have a df, and i group by two columns. i then want to only take the first two rows for my grouped by object. ie

grouped_data = df.groupby(['company','person']).first() 

how do i then select the first two rows for each of these. eg for company = asda there are 8 rows i,e, 9 people under this company but i only want the first two rows. how can i do this using the dataframe above? note i have used first because after grouping by i want to retain the column by column information without aggregation.

If you want frist two rows for each companies you can do:

df.groupby('company').head(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM