繁体   English   中英

获取pandas groupby中元组值列的idxmax或idxmin

[英]Get idxmax or idxmin of tuple-valued column in pandas groupby

我有一个元组值的分数,我想获得与最大值对应的行。 我想做的一个玩具示例是:

import pandas as pd
df = pd.DataFrame({'id': ['a', 'a', 'b', 'b'], 
                   'score': [(1,1,1), (1,1,2), (0, 0, 100), (8,8,8)], 
                   'numeric_score': [1, 2, 3, 4],
                   'value':['foo', 'bar', 'baz', 'qux']})
# Works, gives correct result:
correct_df = df.loc[df.groupby('id')['numeric_score'].idxmax(), :]
# Fails with a TypeError
goal_df = df.loc[df.groupby('id')['score'].idxmax(), :] 

correct_df有我想要的结果goal_df 这会引发一堆错误,其核心似乎是:

TypeError: reduction operation 'argmax' not allowed for this dtype

一个有效但丑陋的解决方案是:

best_scores = df.groupby('id')['score'].max().reset_index()[['id', 'score']]
goal_df = (pd.merge(df, best_scores, on=['id', 'score'])
           .groupby(['id'])
           .first()
           .reset_index())

有没有这个光滑的版本?

我理解你的问题是:

“NumPy 的.argmax()不适用于元组。对于一系列元组,我如何确定最大值元组的索引?”

IIUC,这将返回所需的结果:

df.loc[df.score == df.score.max()]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM