Python 如何按键访问pandas groupby数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14734533/
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
How to access pandas groupby dataframe by key
提问by beardc
How do I access the corresponding groupby dataframe in a groupby object by the key?
如何通过键访问 groupby 对象中相应的 groupby 数据帧?
With the following groupby:
使用以下 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
But when I try doing that with gb[('foo',)]I get this weird pandas.core.groupby.DataFrameGroupByobject thing which doesn't seem to have any methods that correspond to the DataFrame I want.
但是当我尝试这样做时,gb[('foo',)]我得到了这个奇怪的pandas.core.groupby.DataFrameGroupBy对象,它似乎没有任何与我想要的 DataFrame 相对应的方法。
The best I could think of is:
我能想到的最好的是:
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?
但这有点令人讨厌,考虑到熊猫通常在这些事情上有多好。
这样做的内置方式是什么?
采纳答案by Andy Hayden
You can use the get_groupmethod:
您可以使用以下get_group方法:
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
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.
注意:这不需要为每个组创建一个中间字典/每个子数据帧的副本,因此与使用dict(iter(gb)). 这是因为它使用了 groupby 对象中已经可用的数据结构。
You can select different columns using the groupby slicing:
您可以使用 groupby 切片选择不同的列:
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
回答by JD Margulici
Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:
用于数据分析的 Python 中的 Wes McKinney(pandas 的作者)提供了以下方法:
groups = dict(list(gb))
which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.
它返回一个字典,其键是您的组标签,其值是 DataFrames,即
groups['foo']
will yield what you are looking for:
将产生您正在寻找的内容:
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
回答by LegitMe
Rather than
而不是
gb.get_group('foo')
I prefer using gb.groups
我更喜欢使用 gb.groups
df.loc[gb.groups['foo']]
Because in this way you can choose multiple columns as well. for example:
因为通过这种方式您也可以选择多个列。例如:
df.loc[gb.groups['foo'],('A','B')]
回答by meyerson
I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.
我正在寻找一种方法来对 GroupBy obj 的几个成员进行采样 - 必须解决发布的问题才能完成这项工作。
create groupby object
创建 groupby 对象
grouped = df.groupby('some_key')
pick N dataframes and grab their indicies
选择 N 个数据帧并获取它们的索引
sampled_df_i = random.sample(grouped.indicies, N)
grab the groups
抢组
df_list = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)
optionally - turn it all back into a single dataframe object
可选 - 将其全部转回单个数据帧对象
sampled_df = pd.concat(df_list, axis=0, join='outer')
回答by Surya
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
如果您正在寻找选择性 groupby 对象,请执行以下操作:gb_groups.keys(),并将所需的键输入到以下 key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"

