How do I keep tied rows when taking the top N in pandas?
Short answer
nlargest with keep="all" returns every row tied at the cut-off, rather than arbitrarily dropping one. The default silently picks whichever row came first, which can quietly change your results.
The short version
By default nlargest(n) returns exactly n rows, arbitrarily breaking any tie at the boundary. Pass keep="all" to include every row tied at the cut-off, so you get all the joint winners rather than an arbitrary subset.
The default silently drops a tie
import pandas as pd
s = pd.Series([5, 5, 1])
s.nlargest(1).tolist() # [5] , one of the two fives, arbitrarily
s.nlargest(1, keep="all").tolist() # [5, 5] , both joint winners
Asking for "the top one" when two rows tie has no single right answer, so the default just picks the first. That is fine when any one will do, and quietly wrong when the tie is meaningful.
Why it matters
Imagine reporting "the best-performing city". If two cities tie, the default reports one of them, chosen by row order, and the other disappears. Nobody is told a tie occurred. That is a misleading result produced by an innocuous-looking default.
The keep options
keep="first" (the default) takes the earliest, keep="last" takes the latest, and keep="all" keeps every tied row, which may return more than n rows.
Be ready for that: with keep="all", asking for the top 3 might return 5 rows if there is a three-way tie at third place. That is the honest answer, but any code assuming exactly n rows will need to cope.
The equivalent with rank
The same idea, expressed with rank, works on a whole frame and gives you more control.
df["rank"] = df["amount"].rank(method="min", ascending=False)
df[df["rank"] <= 3] # everyone in the top three, ties included
method="min" gives tied rows the same rank, so a filter of <= 3 naturally keeps every row that shares the boundary rank. This is the pattern to use when you want the top N per group, combining it with groupby.
Sorting and head does not help
df.sort_values("amount", ascending=False).head(3)
This has the same problem: it takes exactly three rows and silently cuts a tie. Sorting does not solve ties; it just hides the arbitrariness behind an ordering.
The decision to make
Ask whether a tie is possible in your data, and if it is, whether it matters. For a leaderboard, a prize or a report, it almost certainly does, and silently dropping a joint winner is a real error. For picking an arbitrary sample row, it does not. Making the choice explicit with keep documents which situation you are in.
Enjoying these?
Go from piecing together answers to real fluency.
Our courses take you from looking things up to doing the work with confidence, step by step on real data.
Browse the courses