Pandas DataFrame nsmallest() Method

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

1. Comprehensive Overview and Method Signature

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.

Method Signature: DataFrame.nsmallest(n, columns, keep='first')

Parameters:
• 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).

Returns: A subset DataFrame containing the n smallest records sorted ascending.

2. Practical Usage Scenarios: Where & Why to Use `nsmallest()`

  • Budget & Discount Identification: Retrieve the 10 lowest-priced items across an e-commerce catalog.
  • Defect & Error Minimization: Extract manufacturing batches exhibiting the lowest failure rates or lowest defect counts.
  • High-Performance Filtering: Querying top/bottom $K$ elements from multi-million row DataFrames without incurring full sorting overhead.

3. Deep Dive Examples & Parameter Manipulations

Example 3.1: Multi-Column Tie Breaking

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

4. Common Errors & Troubleshooting

1. TypeError: Column dtype must be numeric or datetime:
Cause: Attempting to run nsmallest() on string or object columns.
Fix: Convert string columns using pd.to_numeric() before executing nsmallest().

5. Frequently Asked Questions (FAQs)

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).

Interactive Companion Jupyter Notebook

Explore interactive code cells, test multi-column tie breaking, and execute self-validating assertions.

View on GitHub Open In Colab

6. Related Tutorials




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer