Bird
Raised Fist0
Pandasdata~10 mins

nlargest() and nsmallest() in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - nlargest() and nsmallest()
Start with DataFrame
↓
Call nlargest(n, column)
→Sort column descending
↓
Select top n rows
↓
Call nsmallest(n, column)
→Sort column ascending
↓
Select bottom n rows
↓
Return subset DataFrame
Start with a DataFrame, then use nlargest() to get top n rows by a column sorted descending, or nsmallest() to get bottom n rows sorted ascending, returning those rows.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D'], 'Score': [88, 92, 85, 90]})

# Top 2 scores
top_rows = df.nlargest(2, 'Score')
print(top_rows)

# Bottom 2 scores
bottom_rows = df.nsmallest(2, 'Score')
print(bottom_rows)
This code creates a DataFrame with names and scores, assigns and prints the top 2 and bottom 2 rows by Score.
Execution Table
StepActionDataFrame StateResult
1Create DataFrame[{'A',88}, {'B',92}, {'C',85}, {'D',90}]DataFrame with 4 rows
2top_rows = df.nlargest(2, 'Score')Sort 'Score' descendingRows with scores 92 (B), 90 (D)
3print(top_rows)Subset DataFrameRows: B(92), D(90)
4bottom_rows = df.nsmallest(2, 'Score')Sort 'Score' ascendingRows with scores 85 (C), 88 (A)
5print(bottom_rows)Subset DataFrameRows: C(85), A(88)
6EndNo changeExecution complete
💡 All steps executed; nlargest and nsmallest returned correct subsets.
Variable Tracker
VariableStartAfter nlargestAfter nsmallestFinal
df[{'A',88}, {'B',92}, {'C',85}, {'D',90}]UnchangedUnchangedUnchanged
top_rowsN/A[{'B',92}, {'D',90}][{'B',92}, {'D',90}][{'B',92}, {'D',90}]
bottom_rowsN/AN/A[{'C',85}, {'A',88}][{'C',85}, {'A',88}]
Key Moments - 2 Insights
Why does nlargest(2, 'Score') return rows with scores 92 and 90, not 88?
Because nlargest sorts the 'Score' column in descending order and picks the top 2 rows, which are 92 and 90, as shown in execution_table step 2 and 3.
Does nsmallest change the original DataFrame?
No, nsmallest returns a new subset DataFrame without modifying the original, as shown in variable_tracker where 'df' remains unchanged.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what rows does nlargest(2, 'Score') return at step 3?
ARows with scores 92 and 90
BRows with scores 85 and 88
CAll rows sorted ascending
DRows with scores 88 and 85
💡 Hint
Check execution_table row 3 under 'Result' column.
At which step does the DataFrame get sorted ascending by 'Score'?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at execution_table row 4 'Action' column.
If we change nlargest(2, 'Score') to nlargest(3, 'Score'), what changes in variable_tracker?
Adf will be modified
Bbottom_rows will change to 3 rows
Ctop_rows will include 3 rows with highest scores
DNo change at all
💡 Hint
Refer to variable_tracker row for 'top_rows' and how nlargest affects it.
Concept Snapshot
nlargest(n, column) returns top n rows sorted descending by column.
nsmallest(n, column) returns bottom n rows sorted ascending by column.
Both return new DataFrames without changing original.
Use to quickly find highest or lowest values in data.
Full Transcript
We start with a DataFrame of names and scores. Calling nlargest(2, 'Score') sorts the scores descending and picks top 2 rows with scores 92 and 90. Calling nsmallest(2, 'Score') sorts ascending and picks bottom 2 rows with scores 85 and 88. Neither method changes the original DataFrame. The output is subsets of the original data showing highest or lowest values as requested.

Practice

(1/5)
1. What does the nlargest() function in pandas do?
easy
A. Returns rows with the highest values in a specified column
B. Returns rows with the lowest values in a specified column
C. Sorts the entire DataFrame in ascending order
D. Removes duplicate rows based on a column

Solution

  1. Step 1: Understand the purpose of nlargest()

    The nlargest() function is designed to select rows with the highest values in a given column.
  2. Step 2: Compare with other options

    Options B and C describe other functions or behaviors, and D is unrelated to nlargest().
  3. Final Answer:

    Returns rows with the highest values in a specified column -> Option A
  4. Quick Check:

    nlargest() = highest rows [OK]
Hint: Remember: 'n' largest means top values [OK]
Common Mistakes:
  • Confusing nlargest() with nsmallest()
  • Thinking it sorts the whole DataFrame
  • Assuming it removes duplicates
2. Which of the following is the correct syntax to get the 3 smallest values from column 'score' in a DataFrame df?
easy
A. df.nlargest(3, 'score')
B. df.nsmallest(3, 'score')
C. df.nsmallest('score', 3)
D. df.nlargest('score', 3)

Solution

  1. Step 1: Recall the correct method signature

    The correct syntax is df.nsmallest(n, column_name), where n is the number of rows.
  2. Step 2: Match the options with the syntax

    df.nsmallest(3, 'score') matches the correct syntax: df.nsmallest(3, 'score'). Options A and D use nlargest incorrectly, and C has arguments reversed.
  3. Final Answer:

    df.nsmallest(3, 'score') -> Option B
  4. Quick Check:

    nsmallest(n, column) = df.nsmallest(3, 'score') [OK]
Hint: Use nsmallest(n, column) with number first [OK]
Common Mistakes:
  • Swapping arguments order
  • Using nlargest instead of nsmallest
  • Passing column name before number
3. Given the DataFrame:
import pandas as pd
data = {'name': ['Anna', 'Bob', 'Cara', 'Dave'], 'age': [23, 45, 31, 22]}
df = pd.DataFrame(data)

What is the output of df.nlargest(2, 'age')?
medium
A. Rows for Dave and Bob with ages 22 and 45
B. Rows for Anna and Dave with ages 23 and 22
C. Rows for Bob and Cara with ages 45 and 31
D. Rows for Cara and Anna with ages 31 and 23

Solution

  1. Step 1: Identify the ages in the DataFrame

    The ages are Anna: 23, Bob: 45, Cara: 31, Dave: 22.
  2. Step 2: Select the 2 largest ages

    The two largest ages are 45 (Bob) and 31 (Cara).
  3. Final Answer:

    Rows for Bob and Cara with ages 45 and 31 -> Option C
  4. Quick Check:

    nlargest(2, 'age') = Bob, Cara [OK]
Hint: Pick top n values by column with nlargest() [OK]
Common Mistakes:
  • Choosing smallest instead of largest
  • Mixing up row order
  • Confusing names with ages
4. What is wrong with this code snippet?
df.nsmallest('score', 5)

Assuming df is a DataFrame with a column named 'score'.
medium
A. The arguments are in the wrong order
B. The method name should be nlargest
C. The number 5 should be a string
D. The column name should be an integer

Solution

  1. Step 1: Check the method signature for nsmallest()

    The correct order is nsmallest(n, columns), where n is an integer and columns is a string or list.
  2. Step 2: Identify the error in the code

    The code passes the column name first and then the number, which is reversed.
  3. Final Answer:

    The arguments are in the wrong order -> Option A
  4. Quick Check:

    nsmallest(n, column) needs number first [OK]
Hint: Number first, column second in nsmallest() [OK]
Common Mistakes:
  • Swapping argument order
  • Using wrong method name
  • Passing wrong data types
5. You have a DataFrame df with columns ['product', 'price', 'rating']. You want to find the top 3 products with the highest rating but lowest price among those top rated. Which pandas code snippet correctly achieves this?
hard
A. df.nlargest(3, 'rating').nsmallest(3, 'price')
B. df.nlargest(3, 'rating').sort_values('price').head(3)
C. df.nsmallest(3, 'price').nlargest(3, 'rating')
D. df.sort_values(['rating', 'price'], ascending=[False, True]).head(3)

Solution

  1. Step 1: Understand the goal

    We want top 3 products by highest rating, but among those, pick the ones with lowest price.
  2. Step 2: Analyze each option

    df.nlargest(3, 'rating').nsmallest(3, 'price') chains nlargest then nsmallest but nsmallest after nlargest may reduce rows incorrectly. df.nlargest(3, 'rating').sort_values('price').head(3) sorts price after selecting top rating but may not correctly filter lowest price among top rated. df.nsmallest(3, 'price').nlargest(3, 'rating') reverses the order, which is wrong. df.sort_values(['rating', 'price'], ascending=[False, True]).head(3) sorts by rating descending and price ascending, then picks top 3, which correctly prioritizes rating then price.
  3. Final Answer:

    df.sort_values(['rating', 'price'], ascending=[False, True]).head(3) -> Option D
  4. Quick Check:

    Sort by rating desc, price asc, then head(3) [OK]
Hint: Sort by rating desc, price asc, then take top 3 [OK]
Common Mistakes:
  • Chaining nlargest and nsmallest incorrectly
  • Not sorting by both columns properly
  • Selecting wrong rows due to order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard