Pandas: how to get a particular group after groupby? [duplicate]

与世无争的帅哥 提交于 2021-02-18 12:14:45

问题


I want to group a dataframe by a column, called 'A', and inspect a particular group.

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 where A=='foo'.

However, Pandas doesn't work like that.

I couldn't find a similar example online.


回答1:


Try: grouped.get_group('foo'), that is what you need.




回答2:


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    =


来源:https://stackoverflow.com/questions/22702486/pandas-how-to-get-a-particular-group-after-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!