问题描述
如何通过密钥访问groupby对象中相应的groupby数据帧?使用以下组:
How do I access the corresponding groupby dataframe in a groupby object by the key? 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
我想要做一些像
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 do that (well, actually I have to do gb[('foo',)]
), I get this weird pandas.core.groupby.DataFrameGroupBy
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?
推荐答案
您可以使用方法:
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))$ c $创建简单的字典将更加具有更高的内存效率c>。这是因为它使用groupby对象中已经可用的数据结构。
Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient that creating the naive dictionary with dict(iter(gb))
. This is because it uses data-structures already available in the groupby object.
您可以选择不同的列使用groupby切片:
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 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!