import pandas as pd
df = pd.DataFrame({
'Product': ['A', 'B', 'C', 'D'],
'Price': [15.5, 10.0, 25.0, 8.5]
})
print(df.nsmallest(2, 'Price'))
Expected Output:
Product Price
3 D 8.5
1 B 10.0
The DataFrame.nsmallest() method retrieves the first n rows ordered by specified column values in ascending order. Serving as the direct companion method to nlargest(), nsmallest() offers superior computational performance compared to full DataFrame sorting via df.sort_values(col).head(n) because it uses heap-queue algorithms underneath without sorting the entire dataset in RAM.
DataFrame.nsmallest(n, columns, keep='first')n: Integer. Number of smallest rows to return.columns: Column label or list of column labels to sort by.keep: 'first' (default; resolves ties by keeping first occurrence), 'last' (keeps last occurrence), or 'all' (returns all tied rows, even if output length exceeds n).n smallest records sorted ascending.
Pass a list of column names to columns to break ties sequentially when primary column values match.
import pandas as pd
df_items = pd.DataFrame({
'Price': [10, 10, 15, 5],
'Shipping': [5, 2, 1, 4]
})
# Get 2 smallest by Price, breaking ties with Shipping
print(df_items.nsmallest(2, ['Price', 'Shipping']))
Expected Output:
Price Shipping
3 5 4
1 10 2
nsmallest() on string or object columns.pd.to_numeric() before executing nsmallest().
Q: Is nsmallest() faster than sort_values().head()?
Yes, for small values of n relative to total row count, nsmallest() is significantly faster because it uses heap selection ($O(N \log k)$ complexity) instead of full array sorting ($O(N \log N)$ complexity).
Explore interactive code cells, test multi-column tie breaking, and execute self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.