Find Top and Bottom Sales Using nlargest() and nsmallest()
📖 Scenario: You work in a store and have a list of products with their sales numbers. You want to find which products sold the most and which sold the least.
🎯 Goal: Use pandas nlargest() and nsmallest() functions to find the top 3 and bottom 2 selling products from the sales data.
📋 What You'll Learn
Create a pandas DataFrame with product names and their sales numbers.
Create a variable to store the number of top and bottom products to find.
Use nlargest() to find the top 3 selling products.
Use nsmallest() to find the bottom 2 selling products.
Print the results clearly.
💡 Why This Matters
🌍 Real World
Stores and businesses often need to quickly find their best and worst selling products to make decisions about stock and promotions.
💼 Career
Data analysts and data scientists use functions like <code>nlargest()</code> and <code>nsmallest()</code> to summarize and report key insights from sales data.
Progress0 / 4 steps
1
Create the sales DataFrame
Create a pandas DataFrame called sales_data with two columns: 'Product' and 'Sales'. Use these exact entries: 'Apples' with sales 150, 'Bananas' with sales 120, 'Cherries' with sales 90, 'Dates' with sales 200, and 'Elderberries' with sales 50.
Pandas
Hint
Use pd.DataFrame with a dictionary containing the product names and sales numbers.
2
Set the number of top and bottom products
Create two variables: top_n and bottom_n. Set top_n to 3 and bottom_n to 2.
Pandas
Hint
Just create two variables and assign the numbers 3 and 2 to them.
3
Find top and bottom selling products
Use nlargest() on sales_data to find the top top_n products by 'Sales' and store it in top_sellers. Use nsmallest() on sales_data to find the bottom bottom_n products by 'Sales' and store it in bottom_sellers.
Pandas
Hint
Use sales_data.nlargest(top_n, 'Sales') and sales_data.nsmallest(bottom_n, 'Sales').
4
Print the top and bottom sellers
Print the top_sellers DataFrame with the label 'Top Sellers:'. Then print the bottom_sellers DataFrame with the label 'Bottom Sellers:'.
Pandas
Hint
Use print() to show the labels and DataFrames.
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
Step 1: Understand the purpose of nlargest()
The nlargest() function is designed to select rows with the highest values in a given column.
Step 2: Compare with other options
Options B and C describe other functions or behaviors, and D is unrelated to nlargest().
Final Answer:
Returns rows with the highest values in a specified column -> Option A
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
Step 1: Recall the correct method signature
The correct syntax is df.nsmallest(n, column_name), where n is the number of rows.
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.
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
Step 1: Identify the ages in the DataFrame
The ages are Anna: 23, Bob: 45, Cara: 31, Dave: 22.
Step 2: Select the 2 largest ages
The two largest ages are 45 (Bob) and 31 (Cara).
Final Answer:
Rows for Bob and Cara with ages 45 and 31 -> Option C
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
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.
Step 2: Identify the error in the code
The code passes the column name first and then the number, which is reversed.
Final Answer:
The arguments are in the wrong order -> Option A
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
Step 1: Understand the goal
We want top 3 products by highest rating, but among those, pick the ones with lowest price.
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.
Final Answer:
df.sort_values(['rating', 'price'], ascending=[False, True]).head(3) -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.