[python]返回每个分组的top_n

def top_n(df, n=3, column='APM'):
    """
        返回每个分组按 column 的 top n 数据
    """
    return df.sort_values(by=column, ascending=False)[:n]

df_data.groupby('LeagueIndex').apply(top_n)

禁止分组 group_keys=False

df_data.groupby('LeagueIndex', group_keys=False).apply(top_n)
# apply函数接收的参数会传入自定义的函数中
df_data.groupby('LeagueIndex').apply(top_n, n=2, column='Age')

你可能感兴趣的:(python)