Python 过滤最大/最小值
我有一个熊猫数据框,看起来像这样:Python 过滤最大/最小值,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个熊猫数据框,看起来像这样: Player Attempt Score John A 10 John B 20 Mary A 5 Mary B 10 Player Attempt Score John B 20 Mary B 10 如何转换数据帧,以便在每次尝试中仅显示每个玩家的最大或最小分数 在最大情况下,结果如下所示: Player Attempt Score John
Player Attempt Score
John A 10
John B 20
Mary A 5
Mary B 10
Player Attempt Score
John B 20
Mary B 10
如何转换数据帧,以便在每次尝试中仅显示每个玩家的最大或最小分数
在最大情况下,结果如下所示:
Player Attempt Score
John A 10
John B 20
Mary A 5
Mary B 10
Player Attempt Score
John B 20
Mary B 10
这里有一种使用
groupby
+transform
的方法。标记的副本具有更详细的变体
res = df[df['Score'] == df.groupby('Player')['Score'].transform('max')]
print(res)
Player Attempt Score
1 John B 20
3 Mary B 10
由于有人决定在问题结束时回答,这里有一个简短/更好的答案:
df.iloc[df.groupby('Player').Score.idxmax()]
请注意,idxmax
只返回第一个最大值。不同但不是更好。因此,根据您是否想要复制,您有两个选项。