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

当前回答

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

其他回答

除了之前的答案:

以你为例,

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

然后是简单的一行代码

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

提供简洁的格式

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

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

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

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

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

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

为Groupby对象分配一个变量并使用.first()方法。例子:

 a = df_apps_clean[['App', 'Installs']].groupby('Installs')
 a.first()  <----