如何通过键访问pandas groupby数据框 [英] How to access pandas groupby dataframe by key

查看:29
本文介绍了如何通过键访问pandas groupby数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过key访问groupby对象中对应的groupby数据框?

How do I access the corresponding groupby dataframe in a groupby object by the key?

使用以下 groupby:

With the following groupby:

rand = np.random.RandomState(1)
df = pd.DataFrame({'A': ['foo', 'bar'] * 3,
                   'B': rand.randn(6),
                   'C': rand.randint(0, 20, 6)})
gb = df.groupby(['A'])

我可以遍历它以获取键和组:

I can iterate through it to get the keys and groups:

In [11]: for k, gp in gb:
             print 'key=' + str(k)
             print gp
key=bar
     A         B   C
1  bar -0.611756  18
3  bar -1.072969  10
5  bar -2.301539  18
key=foo
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

我希望能够通过密钥访问群组:

I would like to be able to access a group by its key:

In [12]: gb['foo']
Out[12]:  
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

但是当我尝试使用 gb[('foo',)] 这样做时,我得到了这个奇怪的 pandas.core.groupby.DataFrameGroupBy 对象似乎有任何与我想要的 DataFrame 相对应的方法.

But when I try doing that with gb[('foo',)] I get this weird pandas.core.groupby.DataFrameGroupBy object thing which doesn't seem to have any methods that correspond to the DataFrame I want.

我能想到的最好的是:

In [13]: def gb_df_key(gb, key, orig_df):
             ix = gb.indices[key]
             return orig_df.ix[ix]

         gb_df_key(gb, 'foo', df)
Out[13]:
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14  

但这有点令人讨厌,考虑到大熊猫通常在这些事情上有多好.
这样做的内置方式是什么?

but this is kind of nasty, considering how nice pandas usually is at these things.
What's the built-in way of doing this?

推荐答案

您可以使用 get_group 方法:

You can use the get_group method:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

注意:这不需要为每个组创建一个中间字典/每个子数据帧的副本,因此比使用 dict(iter(gb)) 创建简单字典更节省内存.这是因为它使用了 groupby 对象中已经可用的数据结构.

Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient than creating the naive dictionary with dict(iter(gb)). This is because it uses data-structures already available in the groupby object.

您可以使用分组切片选择不同的列:

You can select different columns using the groupby slicing:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64

这篇关于如何通过键访问pandas groupby数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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