我想打印用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

当前回答

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

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

其他回答

我确认了head()的行为在0.12和0.13版本之间发生了变化。我看这像只虫子。我制造了一个问题。

但是groupby操作实际上并不返回按组排序的DataFrame。这里的.head()方法有点误导人——它只是一个方便的特性,可以让您重新检查分组的对象(在本例中为df)。groupby的结果是一个单独类型的对象,一个groupby对象。必须应用、转换或筛选才能返回到数据帧或系列。

如果你想做的只是按列A中的值排序,你应该使用df.sort('A')。

如果你只是在寻找一种显示它的方法,你可以使用describe():

grp = df.groupby['colName']
grp.describe()

这样就得到了一个整洁的表格。

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

python 3

k = None
for name_of_the_group, group in dict(df_group):
    if(k != name_of_the_group):
        print ('\n', name_of_the_group)
        print('..........','\n')
    print (group)
    k = name_of_the_group

以更互动的方式

在Jupyter Notebook中,如果您执行以下操作,它将打印对象的漂亮分组版本。apply方法有助于创建多索引数据框架。

by = 'A'  # groupby 'by' argument
df.groupby(by).apply(lambda a: a[:])

输出:

             A  B
A                
one   0    one  0
      1    one  1
      5    one  5
three 3  three  3
      4  three  4
two   2    two  2

如果您希望by列不出现在输出中,只需删除该列,如下所示。

df.groupby(by).apply(lambda a: a.drop(by, axis=1)[:])

输出:

         B
A         
one   0  0
      1  1
      5  5
three 3  3
      4  4
two   2  2

在这里,我不确定为什么.iloc[:]不能在结尾工作而不是[:]。因此,如果将来由于更新(或当前)而出现一些问题,.iloc[:len(a)]也可以工作。