多指数切片比较

时间:2018-05-21 22:24:45

标签: python pandas multi-index

我正在使用以下婴儿名称数据集: https://raw.githubusercontent.com/hadley/data-baby-names/master/baby-names.csv

其中包含的数据如下:

"year","name","percent","sex"
1880,"John",0.081541,"boy"
1880,"William",0.080511,"boy"
1880,"James",0.050057,"boy"
1880,"Charles",0.045167,"boy"
1880,"George",0.043292,"boy"
1880,"Frank",0.02738,"boy"
1880,"Joseph",0.022229,"boy"

我将所有名字分组在一起,并总结了男孩和女孩的百分比:

data1.groupby(['name','sex'])[['percent']].sum()

创建一个多索引数据框:

   Name    Sex  Percent

   Aaron   boy  0.292292
           girl 0.000805
   Abagail girl 0.001326
   Abbie   boy  0.000092
           girl 0.022804

对于每个名字,我想在一个新的数据框中返回更高的百分比性别:

   Name    Sex  Percent

   Aaron   boy  0.292292
   Abagail girl 0.001326
   Abbie   girl 0.022804

我一直在查看multi-index documentation,但未能弄清楚这一点。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

您可以在groupby tail

之后使用groupby sum
s=df.groupby(['name','sex'])[['percent']].sum()
s.sort_values('Percent').groupby(level=0).tail(1)