#对于以下数据想对每个国家分组,并取age字段前2
df = pd.DataFrame({'Country':['China','China', 'India', 'India', 'America', 'Japan', 'China', 'India'],
'Income':[10000, 10000, 5000, 5002, 40000, 50000, 8000, 5000],
'Age':[5000, 4321, 1234, 4010, 250, 250, 4500, 4321]})
print(df)
# Country Income Age
# 0 China 10000 5000
# 1 China 10000 4321
# 2 India 5000 1234
# 3 India 5002 4010
# 4 America 40000 250
# 5 Japan 50000 250
# 6 China 8000 4500
# 7 India 5000 4321
df.groupby(['Country'])[['Age']].apply(lambda x:x.sort_values(by=['Age'],ascending=False)[:2])
Age
Country
America 4 250
China 0 5000
6 4500
India 7 4321
3 4010
Japan 5 250
这里需要注意一下groupby 操作的几种聚合操作的对比:1.aggregate,2.transform,3.apply,4.fliter
尤其是transform和apply这两个容易混淆。
1.aggregate返回的数据帧只能是标量,每一分组返回的结果只有一行。
2.transform 返回的是向量,返回的值是与数据帧等大小的向量。
3.apply返回的可以是向量也可以是标量。这个函数和上面的aggregate以及transform有区别,上面两者的函数传入的是每个子数据帧的每一列,而这里的apply的函数,传入的是“每个子数据帧的所有列 / 行”,一般默认为列。
所以在这里,transform与aggregate都不合适。