Pandas按索引使用groupby().max()分组取最大值时如何保留其余列?
你当前使用的df1.open_interest.groupby(df1.index).max()属于仅对单列open_interest的Series聚合操作,返回结果自然只会保留分组键和open_interest两列,无法附带同行业的identifier、strike关联字段。
要实现需求,核心是先定位每个分组下open_interest最大值对应的行索引,再从原DataFrame中提取这些行的目标字段,以下是两种常用实现方案:
方案1:性能最优(推荐用于你的26000行场景)
用idxmax定位目标行索引,再提取对应行,运算速度远快于逐组遍历的方案:
# 1. 找到每个分组中open_interest最大值对应的行索引 max_row_idx = df1.groupby(df1.index)['open_interest'].idxmax() # 2. 从原表中提取这些行的指定列,自动附带所有关联字段 result = df1.loc[max_row_idx, ['date', 'open_interest', 'identifier', 'strike']]
如果你的分组是按普通列而非索引划分(比如按date+identifier两列分组),只需修改groupby的参数为对应列名即可:
max_row_idx = df1.groupby(['date', 'identifier'])['open_interest'].idxmax() result = df1.loc[max_row_idx, ['date', 'open_interest', 'identifier', 'strike']]
方案2:逐组提取Top N行
如果后续需要在每个分组下取open_interest前N高的行(比如示例中每个分组取最大的1行),可以直接用groupby的apply方法:
# 每个分组取open_interest最大的1行,保留所有列后筛选目标字段 result = df1.groupby(df1.index, group_keys=False).apply( lambda g: g.nlargest(1, 'open_interest') )[['date', 'open_interest', 'identifier', 'strike']]
补充:如果提取后分组索引需要转为普通列,在最后加一行
result = result.reset_index(drop=True)即可。
内容的提问来源于stack exchange,提问作者Victor Tessaract
相关产品推荐
相关产品推荐

