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

当前回答

你不能直接通过print语句看到groupBy数据,但你可以通过使用for循环迭代组来看到 尝试这段代码以按数据查看组

group = df.groupby('A') #group variable contains groupby data
for A,A_df in group: # A is your column and A_df is group of one kind at a time
  print(A)
  print(A_df)

在尝试之后,您将得到一个输出作为groupby结果

我希望这对你们有帮助

其他回答

这是一个更好的通用答案。此函数将打印所有组名和值,或可选地选择一个或多个组进行显示。

def print_pd_groupby(X, grp=None):
    '''Display contents of a Panda groupby object
    :param X: Pandas groupby object
    :param grp: a list with one or more group names
    '''
    if grp is None:
        for k,i in X:
            print("group:", k)
            print(i)
    else:
        for j in grp:
            print("group:", j)
            print(X.get_group(j))

在您的示例案例中,下面是会话输出

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

In [117]: dfg = df.groupby('A')

In [118]: print_pd_groupby(dfg)
group: one
     A  B
0  one  0
1  one  1
5  one  5
group: three
       A  B
3  three  3
4  three  4
group: two
     A  B
2  two  2

In [119]: print_pd_groupby(dfg, grp = ["one", "two"])
group: one
     A  B
0  one  0
1  one  1
5  one  5
group: two
     A  B
2  two  2

这是一个更好的答案,因为函数是可重用的内容,把它放在你的包或函数集合中,永远不要重新编写那种“脚本化”的方法。

恕我直言,类似这样的东西应该是熊猫组的内置方法。

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

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

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

只是做的事:

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['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对象。输出看起来不错。 缺点是会产生一系列冗余数据。

另一个简单的选择:

for name_of_the_group, group in grouped_dataframe:
   print (name_of_the_group)
   print (group)