如何打印分组对象 [英] How to print a groupby object
本文介绍了如何打印分组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要打印与熊猫分组的结果.
I want to print the result of grouping with Pandas.
我有一个数据框:
import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
print(df)
A B
0 one 0
1 one 1
2 two 2
3 three 3
4 three 4
5 one 5
按"A"分组后进行打印时,我有以下内容:
When printing after grouping by 'A' I have the following:
print(df.groupby('A'))
<pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>
如何打印分组的数据框?
How can I print the dataframe grouped?
如果我这样做:
print(df.groupby('A').head())
我获得的数据框好像没有分组一样:
I obtain the dataframe as if it was not grouped:
A B
A
one 0 one 0
1 one 1
two 2 two 2
three 3 three 3
4 three 4
one 5 one 5
我期待的是类似的东西
A B
A
one 0 one 0
1 one 1
5 one 5
two 2 two 2
three 3 three 3
4 three 4
推荐答案
只需这样做:
grouped_df = df.groupby('A')
for key, item in grouped_df:
print(grouped_df.get_group(key), "\n\n")
这也可以,
grouped_df = df.groupby('A')
gb = grouped_df.groups
for key, values in gb.iteritems():
print(df.ix[values], "\n\n")
用于选择性键分组:使用gb.keys()
在下面将所需的键插入key_list_from_gb
内:例如,
For selective key grouping: Insert the keys you want inside the key_list_from_gb
, in following, using gb.keys()
: For Example,
gb = grouped_df.groups
gb.keys()
key_list_from_gb = [key1, key2, key3]
for key, values in gb.items():
if key in key_list_from_gb:
print(df.ix[values], "\n")
这篇关于如何打印分组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文