访问Pandas中的群组

时间:2014-02-24 02:38:22

标签: python pandas

假设我有一些随机数据框:

> df
     A      B         C         D
0  foo    one  1.344866 -0.602697
1  bar    one  0.669491 -0.264758
2  foo    two  0.830100  0.381644
3  bar  three -0.756694 -0.382337
4  foo    two -0.267778  0.963123
5  bar    two  1.275177 -0.667924
6  foo    one  0.240863  0.321022
7  foo  three -1.431863 -0.333058

我按照以下方式对其进行分区:

groups =df.groupby(['A', 'B'])

以下两种方法有什么区别?他们以不同的格式返回群组信息。

使用键,值对:

for key, value in groups:
  print key
  print value

使用nth():

for group_ix in xrange(groups.ngroups)
  item = groups.nth(group_ix)

1 个答案:

答案 0 :(得分:3)

这两件事情完全不同,nth获取组中的第n个值(如果该组的项数少于n个,则当前使用NaN):

In [11]: groups.nth(n=0)  # the 0th items in each group
Out[11]:
                  C         D
A   B
bar one    0.669491 -0.264758
    three -0.756694 -0.382337
    two    1.275177 -0.667924
foo one    1.344866 -0.602697
    three -1.431863 -0.333058
    two    0.830100  0.381644

In [12]: groups.nth(n=1)  # the 1st items in each group, NaNs if <=1
Out[12]:
                  C         D
A   B
bar one         NaN       NaN
    three       NaN       NaN
    two         NaN       NaN
foo one    0.240863  0.321022
    three       NaN       NaN
    two   -0.267778  0.963123

注意:atm并没有特别详细记录,有一个未解决的问题是改变它并使用Series groupby调整nth的行为(为cumcount() == n)。

当您遍历组时,您将获得键(mi)和值(每个组的subDataFrame):

In [21]: for k, v in groups: print k  # the v are subDataFrames for each item
('bar', 'one')
('bar', 'three')
('bar', 'two')
('foo', 'one')
('foo', 'three')
('foo', 'two')

In [22]: groups.get_group(('foo' , 'one'))  # example v
Out[22]:
     A    B         C         D
0  foo  one  1.344866 -0.602697
6  foo  one  0.240863  0.321022