如何获得多列分组中的第一组? [英] How to get the first group in a groupby of multiple columns?

查看:76
本文介绍了如何获得多列分组中的第一组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我申请 groupby 之后,我一直在想如何只返回第一组.

I've been trying to figure out how I can return just the first group, after I apply groupby.

我的代码是这样的:

gb = df.groupby(['col1', 'col2', 'col3', 'col4'])['col5'].sum()

我想要的是第一组输出.我一直在尝试 get_group 方法,但它一直失败(可能是因为我按多列分组?)

What I want is for that first first group to output. I've been trying the get_group method but it keeps failing (maybe because I am grouping by multiple columns?)

这是我的输出示例:

col1  col2  col3   col4  'sum'
 1     34   green   10    0.0
            yellow  30    1.5 
            orange  20    1.1 
 2     89   green   10    3.0 
            yellow   5    0.0 
            orange  10    1.0

我想要的只是这个:

col1  col2  col3   col4  'sum'
 1     34   green   10    0.0
            yellow  30    1.5 
            orange  20    1.1 

(注意我刚刚在此处添加的sum"列以明确最后一列是什么,但 pandas 实际上并未命名该列)

(Note the 'sum' column I just added here to make it clear what that last column was, but pandas does not actually name that column)

推荐答案

您可以将 get_groupgroups

g=df.groupby(['col1','col2'])

g.get_group((list(g.groups)[0])).groupby(['col3','col4'])['col5'].sum()

这篇关于如何获得多列分组中的第一组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆