我想打印用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”分组后打印时,我有以下内容:

print(df.groupby('A'))

<pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>

如何打印分组的数据框架?

如果我这样做:

print(df.groupby('A').head())

我获得的数据帧好像它没有分组:

             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

当前回答

df.groupby('key you want to group by').apply(print)

正如其他成员所提到的,这是可视化groupby对象的最简单的解决方案。

其他回答

另外,其他简单的选择可以是:

gb = df.groupby("A")
gb.count() # or,
gb.get_group(your_key)
df.groupby('A').apply(display)

提供简洁的格式

只是做的事:

grouped_df = df.groupby('A')

for key, item in grouped_df:
    print(grouped_df.get_group(key), "\n\n")

弃用通知:ix在0.20.0中已弃用

这也是可行的,

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,在下面:

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")

除了之前的答案:

以你为例,

df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})

然后是简单的一行代码

df.groupby('A').apply(print)

你只需要将DataFrameGroupBy对象转换为列表,你可以简单地打印它。 ls_grouped_df = list(df.groupby('A')) 打印(ls_grouped_df)