Skip to content

Instantly share code, notes, and snippets.

@qiuyujx
Created September 27, 2020 13:19
Show Gist options
  • Save qiuyujx/7d788717b51db3c878f769c159c69fc2 to your computer and use it in GitHub Desktop.
Save qiuyujx/7d788717b51db3c878f769c159c69fc2 to your computer and use it in GitHub Desktop.
def find_max_in_group(df, group_col, val_col, tie_for_first=False):
# Decide ranking method
if tie_for_first:
rank_method = 'min'
else:
rank_method = 'first'
# Add rank number for each group
df["rank"] = df.groupby(group_col)[val_col].rank(method=rank_method, ascending=False)
# Only return rank == 1
return df[df['rank'] == 1].drop(['rank'], axis=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment