pandas :如何在每个GROUP BY组中选择第一行? [英] pandas: how do I select first row in each GROUP BY group?

查看:110
本文介绍了 pandas :如何在每个GROUP BY组中选择第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择每个GROUP BY组中的第一行基本相同吗? 仅在熊猫中.

df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
                'B' : ['3', '1', '2', '4','2', '4', '1', '3'],
                    })

排序似乎很有希望:

df.sort('B')

     A  B
1  foo  1
6  bar  1
2  foo  2
4  bar  2
0  foo  3
7  bar  3
3  foo  4
5  bar  4

但是首先不会给出期望的结果... df.groupby('A').first()

But then first won't give the desired result... df.groupby('A').first()

     B
A     
bar  2
foo  3

推荐答案

通常,如果您希望以分组方式对数据进行排序,但不是要分组的列之一,则最好使用 sort df groupby:

Generally if you want your data sorted in a groupby but it's not one of the columns which are going to be grouped on then it's better to sort the df prior to performing groupby:

In [5]:
df.sort_values('B').groupby('A').first()

Out[5]:
     B
A     
bar  1
foo  1

这篇关于 pandas :如何在每个GROUP BY组中选择第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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