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

当前回答

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

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

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

其他回答

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

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

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

感谢Surya的深刻见解。我会清理他的解决方案,简单地做:

for key, value in df.groupby('A'):
    print(key, value)
df.groupby('key you want to group by').apply(print)

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

打印所有(或任意多行)的分组df:

import pandas as pd
pd.set_option('display.max_rows', 500)

grouped_df = df.group(['var1', 'var2'])
print(grouped_df)

我发现了一个棘手的方法,只是为了头脑风暴,见代码:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)

输出:

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

优点是很容易打印,因为它返回一个数据帧,而不是Groupby对象。输出看起来不错。 缺点是会产生一系列冗余数据。