Pandas:如何在 groupby 之后获得特定的组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22702486/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: how to get a particular group after groupby?
提问by zer0ne
I want to group a dataframe by a column, called 'A', and inspect certain certain group.
我想按名为“A”的列对数据框进行分组,并检查某些特定组。
grouped = df.groupby('A', sort=False)
However, I don't know how to access a group, for example, I expect that
但是,我不知道如何访问组,例如,我希望
grouped.first() 
would give me the first group
会给我第一组
Or
或者
grouped['foo'] 
would give me the group A=='foo'.
会给我 A=='foo' 组。
However, Pandas doesn't work like that.
但是,Pandas 不是这样工作的。
I couldn't find a similar example online.
我在网上找不到类似的例子。
回答by CT Zhu
Try: grouped.get_group('foo'), that is what you need. 
尝试:grouped.get_group('foo'),这就是您所需要的。
回答by Paul H
from io import StringIO # from StringIO... if python 2.X
import pandas
data = pandas.read_csv(StringIO("""\
area,core,stratum,conc,qual
A,1,a,8.40,=
A,1,b,3.65,=
A,2,a,10.00,=
A,2,b,4.00,ND
A,3,a,6.64,=
A,3,b,4.96,=
"""), index_col=[0,1,2])
groups = data.groupby(level=['area', 'stratum'])
groups.get_group(('A', 'a')) # make sure it's a tuple
                    conc qual
area core stratum            
A    1    a         8.40    =
     2    a        10.00    =
     3    a         6.64    =

