Skip to main content
v2026.11,986 entries · CC-BY 4.0

pandas nlargest: DataFrame and Series Syntax, keep and Ties

pandas nlargest syntax for DataFrame and Series, how keep handles ties, a worked example, and the TypeError for text columns, from the official docs.

Written and maintained by CASRAI Editorial Board

Published

On this page

pandas nlargest returns the rows (DataFrame.nlargest) or values (Series.nlargest) with the largest values, ordered from largest to smallest, without sorting the whole table yourself. In a DataFrame you call df.nlargest(n, columns), for example the ten studies with the biggest sample size; in a Series you call s.nlargest(n). A third argument, keep, decides what happens when several rows tie at the cut-off, and that argument is where most surprises come from.

What pandas nlargest is used for in research

Research tables are full of ranking questions: which sites enrolled the most participants, which genes show the highest expression, which grants carry the largest awards, which journals contributed the most records to a corpus. nlargest answers each of them in one call and keeps the other columns of each row, so the result is still a usable table rather than a bare list of numbers.

The pandas documentation states that DataFrame.nlargest(n, columns, keep='first') returns the first n rows ordered by columns in descending order, that the other columns are returned but not used for ordering, and that the call is equivalent to df.sort_values(columns, ascending=False).head(n) but more performant. Its mirror image is nsmallest, which the same documentation describes as the ascending equivalent of sort_values(columns, ascending=True).head(n).

DataFrame.nlargest and Series.nlargest compared

The two methods share the name but not the signature. DataFrame.nlargest(n, columns, keep='first') has no default for n and needs the label (or list of labels) of the column(s) to rank by. Series.nlargest(n=5, keep='first') has no columns argument because a Series is one column, and its n defaults to 5, so s.nlargest() with no arguments returns five values. Both accept the same three keep options.

How to install or access pandas

The official installation page describes two routes: pip install pandas, and conda install -c conda-forge pandas. It recommends installing into a dedicated environment, for example conda create -c conda-forge -n name_of_my_env python pandas, so that analysis projects do not interfere with each other. Optional extras are installed with commands such as pip install "pandas[excel]", pip install "pandas[performance]" or pip install "pandas[all]".

Which Python version a given pandas release needs is defined by the pandas Python support policy referenced from the installation page, so check that page for your interpreter rather than assuming. Once installed, import pandas as pd is all that is needed; nlargest is a method on the DataFrame and Series objects, not a separate import. To see which release you have, print pd.__version__. The examples below were run with pandas 3.1.1, the version whose documentation is cited in the sources.

How to select the largest rows with nlargest step by step

The steps below use a small, invented table of eight study sites, labelled as an illustrative composite: the site names and numbers are made up for demonstration, and the outputs shown were produced by running the code in pandas 3.1.1. The columns are site, n (participants enrolled) and effect (an estimated effect size).

  1. Build or load the table. df = pd.DataFrame({'site': list('ABCDEFGH'), 'n': [120, 85, 120, 60, 200, 85, 120, 40], 'effect': [0.31, 0.42, 0.28, 0.55, 0.12, 0.42, 0.35, 0.60]}). In real work this is usually pd.read_csv(...).
  2. Check that the ranking column is numeric. Run df.dtypes. nlargest cannot rank object or category columns (see troubleshooting below), so convert first if needed; the CASRAI guide to pandas dtypes covers inspecting and converting types.
  3. Call nlargest with n and the column. df.nlargest(3, 'n') returns the three sites with the largest n.
  4. Decide how ties are handled. Three sites (A, C and G) share 120 participants, but only two slots remain after site E (200). Add keep='first' (the default), keep='last' or keep='all' as described in the tie table below.
  5. Break ties with a second column if the analysis needs a unique ranking. Pass a list: df.nlargest(3, ['n', 'effect']). The first column ranks; the next columns settle ties.
  6. Use the result. The return value is a new DataFrame, so you can chain it, for example df.nlargest(3, 'effect')['site'].tolist(), which returned ['H', 'D'] for nlargest(2, 'effect') in this example.

Ranking by several columns

When columns is a list, rows are ordered by the first column and ties are broken by the next. In the example, df.nlargest(3, ['n', 'effect']) returned sites E (200, 0.12), G (120, 0.35) and A (120, 0.31): among the three sites tied at 120, the higher effect won. Site C (120, 0.28) lost the tie-break. The official documentation shows the same behaviour on its country example, where nlargest(3, ['population', 'GDP']) returns France, Italy and Brunei, because Brunei has the highest GDP among the three countries tied at 434,000 population.

How to read the output

The output is a DataFrame whose index labels are the original index labels of the selected rows, not a fresh 0 to n-1 count. In the example, df.nlargest(3, 'n') printed rows with index 4, 0 and 2 (sites E, A and C). That is deliberate: it lets you trace each row back to the source table. Call .reset_index(drop=True) if you want a clean count, or keep the labels when you will join the result back.

Rows are ordered by the ranking column from largest to smallest, so the first row is the maximum. On a Series the result is a Series with the same index labels, for instance df['effect'].nlargest(3) returned labels 7, 3 and 1 with values 0.60, 0.55 and 0.42.

How keep decides ties

Tied values are the only case where keep matters. The documentation defines first as prioritising the first occurrence(s), last as prioritising the last occurrence(s), and all as keeping all the ties of the smallest item even if that means returning more than n rows. On the illustrative table, keep='first' returned E, A and C; keep='last' returned E, G and C; and keep='all' returned four rows, E, A, C and G, because all three 120s were kept. The data table below compares the three options on the official documentation example.

The practical rule: use keep='all' when dropping a tied row would misrepresent the ranking (for example, reporting the top three sites while hiding a fourth site with an identical count), and accept that the result may then exceed n. Use the default when you need exactly n rows and the order of the source table is an acceptable tie-break. For a ranking whose tie-break is a documented rule, prefer a second column over relying on row order.

nlargest, sort_values and idxmax

The documentation presents nlargest as equivalent to sort_values(columns, ascending=False).head(n), only more performant. For a Series it adds that nlargest is faster than sort_values(ascending=False).head(n) when n is small relative to the length of the Series. DataFrame.sort_values defaults to kind='quicksort', and its documentation notes that only mergesort and stable are stable (preserve the relative order of equal keys). kind is applied only when sorting on a single column. If you need the single largest value’s label rather than a ranked table, the CASRAI guide to idxmax in pandas covers that case.

Troubleshooting pandas nlargest

TypeError: cannot use method ‘nlargest’ with this dtype

The official notes say that nlargest cannot be used with all column types: specifying columns with object or category dtypes raises TypeError. In the run used for this page (pandas 3.1.1) a text column raised TypeError: Column 'lab' has dtype str, cannot use method 'nlargest' with this dtype, and a category column raised the same message with category. A text column holding digits, such as df['n'].astype(str), is also rejected. The fix is to convert the column to a numeric type yourself before ranking, for example with pd.to_numeric, after checking what the conversion does to non-numeric entries.

KeyError on the column name

df.nlargest(2, 'missing') raised KeyError: 'missing'. Column labels are case sensitive and exact; print df.columns and copy the label, including any spaces.

The result has more rows than n

That is keep='all' working as documented: it keeps all ties of the smallest selected item. Switch to keep='first' or keep='last', or add a second ranking column, if you need exactly n rows.

Different rows when you reorder the source

With keep='first' or 'last', which of several tied rows survives depends on their order of appearance in the table. If the table is re-sorted or re-read in a different order between runs, tied rows can change. Make the tie-break explicit with a second column, or sort deterministically before ranking, so the result is reproducible in a methods section or analysis script.

Missing values

If a ranking column contains NaN, check the output on a small sample before relying on it. If you need a defined rule, drop or fill the missing values first and say which you did in your analysis notes. Related clean-up steps, such as removing repeated records before ranking, are covered in the CASRAI guide to pandas drop_duplicates.

Ranking within groups

nlargest ranks the whole table. For the top rows within each group (for example the largest sites per country), the usual approach is to group first and then rank within each group. When a table has a hierarchical index, see the CASRAI guide to MultiIndex in pandas before selecting or sorting.

Free alternatives to pandas nlargest

pandas is not the only way to get a top-n selection. The table lists alternatives, each with what its own documentation says. For NumPy-based index ranking, see the CASRAI guide to numpy argsort.

Alternative What its documentation says
pandas sort_values(columns, ascending=False).head(n) Described in the nlargest documentation as the equivalent of nlargest, but less performant. Gives you control over kind for single-column sorts.
pandas nsmallest(n, columns, keep='first') The ascending counterpart: equal to sort_values(columns, ascending=True).head(n); keep='all' may return more than n rows.
Python standard library heapq.nlargest(n, iterable, key=None) Returns a list of the n largest elements, equivalent to sorted(iterable, key=key, reverse=True)[:n]; the documentation says it performs best for smaller n, and that for larger n sorted() is more efficient.
Polars DataFrame.top_k(k, by=..., reverse=False) Returns the k largest rows (or smallest with reverse=True); the output is not guaranteed to be in any particular order, so call sort() afterwards if you need ordering.

The one difference that matters when migrating from pandas to Polars is ordering: its top_k output is unordered unless you sort it, whereas nlargest returns rows ordered by the ranking columns.

Sources

Data: pandas nlargest keep options on the official documentation example

Compares what DataFrame.nlargest returns on the pandas documentation's nine-country example for each keep option and for a two-column call. Compiled from the DataFrame.nlargest documentation page, which lists the example outputs.

pandas nlargest keep options on the official documentation example
CallRows returned (rows)Row labels returned (in order)Documented rule
nlargest(3, 'population')3France, Italy, Maltakeep='first' (default) prioritises the first occurrence(s) among ties
nlargest(3, 'population', keep='last')3France, Italy, Bruneikeep='last' prioritises the last occurrence(s) among ties
nlargest(3, 'population', keep='all')5France, Italy, Malta, Maldives, Bruneikeep='all' keeps all ties of the smallest item, even if more than n rows result
nlargest(3, ['population', 'GDP'])3France, Italy, BruneiLater columns in the list break ties in the earlier column

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about pandas nlargest: DataFrame and Series Syntax, keep and Ties

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →