Knowledge base / Python

pandas nsmallest: smallest values and boundary ties

I show which records are selected, when results exceed n and how to define tie-breaking correctly.

Kajo RudzińskiPublished Updated 5 min read

A mechanical selector choosing short cube stacks from a larger collection.

When I need a few smallest values together with the other fields in each record, I use DataFrame.nsmallest(). Before choosing n, I define the tie rule. “The two cheapest products” can mean exactly two records or all products tied at the selection boundary. Repeated prices make those different definitions produce different results.

This entry follows pandas 3.1.1. The data are synthetic and prices use arbitrary units. I separate input order, price and an additional numeric priority so the selection rule is visible. nsmallest is a Series or DataFrame method, rather than a standalone pd.nsmallest() function.

Select complete rows by price

DataFrame.nsmallest returns rows ordered increasingly by the specified columns. Other columns are also returned but do not participate in ordering. Prepare five records in this order:

import pandas as pd

products = pd.DataFrame({
    "product": ["A", "B", "C", "D", "E"],
    "price": [30, 10, 20, 10, 10],
    "priority": [1, 3, 2, 1, 2],
})
cheapest = products.nsmallest(2, "price", keep="first")
Index Product Price Priority
1 B 10 3
3 D 10 1

The lowest price is 10, shared by B, D and E. With keep="first", B and D take the first two places according to input order. The priority column does not matter here because I did not include it in columns. Product names are not an implicit secondary key either. The result retains the selected records’ index labels rather than renumbering them from zero.

first, last and all

For exactly the same data, the three settings produce these selections:

Call with n = 2 on price Products in result order
keep="first" B, D
keep="last" E, D
keep="all" B, D, E

The last option prefers later occurrences and reverses their order within a tie. It does not select the largest values or the latest dates stored in another column. The all option preserves ties at the boundary, so the result can contain more than n rows. If an interface has room for two items, I need to decide how it should display three validly selected records.

This is still a selection of observations rather than n distinct prices. With n = 2 and all, I do not proceed to price 20 just to obtain a second unique price level. The two smallest observations both cost 10, and retaining their boundary ties produces three records at that price. The Series.nsmallest documentation makes the tie policies explicit too.

An expanding tray accommodating three equally low stacks at the selection boundary

A second key must be supported

You can pass multiple columns. The first decides the primary order, and subsequent columns break ties. With our numeric priority:

with_priority = products.nsmallest(2, ["price", "priority"])

The result contains D followed by E. All cheapest products cost 10, with priorities 1 for D, 2 for E and 3 for B. Both keys are ascending. Naming a column “priority” does not reverse its direction automatically. Here, a smaller priority number takes precedence; establish that meaning explicitly in a real report.

I do not use products.nsmallest(2, ["price", "product"]) to break ties alphabetically. A string column is unsupported as a selection key and raises TypeError. This type restriction is also visible in the official pandas 3.1.1 selection implementation. Text can remain among the returned fields, as in our result. The restriction concerns columns used for selection.

When I use sort_values

For ascending price followed by alphabetical product name, I use sort_values:

by_name = products.sort_values(["price", "product"]).head(2)

With our names A, B, C, D and E, this returns B and D. The textual tie-breaker is explicit, rather than an accidental consequence of input order. sort_values also supports different ascending directions across columns. If all specified keys still tie, a reproducible selection needs another rule, such as a stable identifier. Sorting by name cannot separate two identical names by itself.

Calling head(2) without first establishing order returns the first two rows, A and B. It does not search for minima. Selecting the smallest n rows from the whole frame also differs from selecting n within each group. Regional product rankings require a group-level definition and a plan for combining results. This entry selects from one complete DataFrame.

Types, missing values and what minimum means

Before using the selection in a report, I check that price is numeric. A text column containing “10” and “30” needs type preparation even if its display looks numerical. If records without a price should be ineligible, I can explicitly prepare eligible = products.dropna(subset=["price"]). The dropna documentation explains how subset restricts the checked columns. That avoids accidentally excluding a record because an unrelated description is missing.

All prices are complete in this example. For real data I inspect the excluded count and whether zero means a valid price, an error marker or something else. nsmallest follows a numerical selection rule; it cannot define “cheapest available product.” Availability, package units and the applicable price period may require filters. Establish those conditions before ranking.

Performance and an exercise

The documentation presents nsmallest as specialized selection, and for Series identifies an advantage when n is small relative to the data length. I do not turn that into a guaranteed speedup or memory saving for every file. First check supported types and required ordering. For the opposite selection, there is also nlargest.

For an exercise, change E’s price from 10 to 5. With n = 2 and keep="all", the result should contain E plus both products at the next price of 10: B and D. Explain why three rows remain even though their prices are no longer identical. Then define a selection rule for a report that strictly permits two items. This prevents a later attempt to “repair” a valid result by arbitrarily truncating it.

Key takeaways

Does keep="all" always return n rows?

It can return more because it retains boundary ties. In the example, n=2 selects three products priced at 10.

Can nsmallest order by product name?

A string column is unsupported as a selection key. Use sort_values on price and name, followed by head.

What does keep="last" mean?

For ties, it prefers the last input occurrences and returns them in reverse occurrence order. It does not mean selecting the largest value.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.