如何使用Pandas获取每月的Top5最大值?
获取每月前5个最大值的Pandas解决方案
Got it, let's figure out how to grab the top 5 largest balance values per month instead of just the single max! Here are a couple of straightforward, practical approaches that work perfectly in Pandas:
方法1:Groupby + Nlargest(推荐,灵活度拉满)
如果你的DataFrame还没把日期设为索引,先搞定这一步,然后按月份周期分组,直接提取每组的前5最大值:
# 先确保日期列是datetime类型(如果还没转换的话) df['date_col'] = pd.to_datetime(df['date_col']) # 将日期设为索引 df = df.set_index('date_col') # 按月份分组,提取balance列的前5最大值 top5_monthly = df.groupby(df.index.to_period('M'))['balance'].nlargest(5)
这个方法会保留原始的日期索引,方便你查看每个最大值对应的具体日期。想要更整洁的表格结构?加个reset_index()就行:
top5_monthly = df.groupby(df.index.to_period('M'))['balance'].nlargest(5).reset_index(name='top_balance')
如果你的DataFrame还有其他列(比如交易备注、用户ID),想要同时获取这些top5记录的完整信息,调整下代码就可以:
top5_monthly_full = df.groupby(df.index.to_period('M')).apply(lambda x: x.nlargest(5, 'balance')).reset_index(drop=True)
方法2:结合Resample + Apply
如果你习惯用resample的语法,也可以通过apply调用nlargest来实现:
top5_monthly = df['balance'].resample('M').apply(lambda x: x.nlargest(5))
返回的结果是多层索引(第一层是月份,第二层是原始日期),同样可以用reset_index()整理成扁平化的表格。
小提醒
- 一定要确认日期列是datetime格式,不然分组/重采样会直接报错,用
pd.to_datetime()转换就好。 - 如果某个月份的记录不足5条,
nlargest会返回该月所有的记录,不会强行补空值,这点很人性化~
内容的提问来源于stack exchange,提问作者jason
相关产品推荐
相关产品推荐

