"Top N per group" is one of the most common real queries in analytics, and the naive implementation — groupby(...).apply(lambda g: g.nlargest(n)) — is both the slow answer and, once two rows tie, an answer that is not even deterministic.
Write top_n_per_group(df, n). Given a DataFrame with group, id and score columns, return the top n rows per group by score descending.
Ties in score are broken by id ascending, always — two runs on the same input must return the identical rows in the identical order. A group with fewer than n rows returns all of them; nothing is padded and nothing raises.
You have read the opening. The rest is free with a Bezen account, and no card is needed.
Behind the sign-in