当您只使用
df.groupby('A')你得到一个
GroupBy对象。此时您尚未对其应用任何功能。在幕后,虽然这个定义可能并不完美,但是您可以将
groupby对象视为:
- (组,Dataframe) 对的迭代器,用于Dataframe,或
- 系列 的 (组,系列) 对的迭代器。
为了显示:
df = Dataframe({'A' : [1, 1, 2, 2], 'B' : [1, 2, 3, 4]})grouped = df.groupby('A')# each `i` is a tuple of (group, Dataframe)# so your output here will be a little messyfor i in grouped: print(i)(1, A B0 1 11 1 2)(2, A B2 2 33 2 4)# this version uses multiple counters# in a single loop. each `group` is a group, each# `df` is its corresponding Dataframefor group, df in grouped: print('group of A:', group, 'n') print(df, 'n')group of A: 1 A B0 1 11 1 2group of A: 2 A B2 2 33 2 4# and if you just wanted to visualize the groups,# your second counter is a "throwaway"for group, _ in grouped: print('group of A:', group, 'n')group of A: 1group of A: 2现在至于
.head。只需查看该方法的文档即可:
本质上等同于
.apply(lambda x: x.head(n))
所以在这里,您实际上是在对groupby对象的每个组应用一个函数。请记住,每个组
.head(5)都 适用
于每个组,因此,由于每个组少于或等于5行,因此可以得到原始的Dataframe。
在上面的示例中考虑这一点。如果使用
.head(1),则仅获得每个组的第一行:
print(df.groupby('A').head(1)) A B0 1 12 2 3


