简体   繁体   English

在我的多索引 pandas dataframe 中,我怎么能 select 只为每个级别(0)的前两行?

[英]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.说我有一个df,我按两列分组。 i then want to only take the first two rows for my grouped by object.然后,我只想为按 object 分组的前两行。 ie IE

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

how do i then select the first two rows for each of these.然后我该怎么做 select 每个这些的前两行。 eg for company = asda there are 8 rows i,e, 9 people under this company but i only want the first two rows.例如,对于公司 = asda,有 8 行,即这家公司下有 9 人,但我只想要前两行。 how can i do this using the dataframe above?我怎样才能使用上面的 dataframe 做到这一点? 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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