Sorting Data in Ascending and Descending Order with pandas
📖 Scenario: You work in a small bookstore. You have a list of books with their prices. You want to see the books sorted by price from cheapest to most expensive, and also from most expensive to cheapest.
🎯 Goal: Learn how to sort data in ascending and descending order using pandas DataFrame.
📋 What You'll Learn
Create a pandas DataFrame with book titles and prices
Create a variable to control sorting order
Sort the DataFrame by price in ascending or descending order based on the variable
Print the sorted DataFrame
💡 Why This Matters
🌍 Real World
Sorting data is common in stores to show products from cheapest to most expensive or vice versa, helping customers make choices.
💼 Career
Data scientists often sort data to analyze trends, prepare reports, or clean data before deeper analysis.
Progress0 / 4 steps
1
Create the books DataFrame
Create a pandas DataFrame called books with two columns: 'Title' and 'Price'. Use these exact entries: 'The Alchemist' priced at 10, '1984' priced at 15, 'Python 101' priced at 20, 'Data Science' priced at 25.
Pandas
Hint
Use pd.DataFrame with a dictionary where keys are column names and values are lists of data.
2
Set the sorting order variable
Create a variable called ascending_order and set it to True to indicate sorting in ascending order.
Pandas
Hint
Just create a variable named ascending_order and assign True to it.
3
Sort the DataFrame by price
Create a new DataFrame called sorted_books by sorting books by the 'Price' column. Use the ascending_order variable to decide if sorting is ascending or descending.
Pandas
Hint
Use books.sort_values(by='Price', ascending=ascending_order) to sort.
4
Print the sorted DataFrame
Print the sorted_books DataFrame to see the books sorted by price.
Pandas
Hint
Use print(sorted_books) to display the sorted DataFrame.
Practice
(1/5)
1. What does setting ascending=False do when sorting a pandas DataFrame?
easy
A. Sorts the data from largest to smallest values
B. Sorts the data from smallest to largest values
C. Leaves the data unsorted
D. Sorts the data alphabetically only
Solution
Step 1: Understand the ascending parameter
The ascending parameter controls the order of sorting: True means smallest to largest, False means largest to smallest.
Step 2: Apply the meaning of ascending=False
Setting ascending=False sorts the data from the largest values down to the smallest values.
Final Answer:
Sorts the data from largest to smallest values -> Option A
Quick Check:
ascending=False = largest to smallest [OK]
Hint: False means descending order, largest first [OK]
Common Mistakes:
Confusing ascending=False with ascending=True
Thinking it sorts alphabetically only
Assuming it leaves data unsorted
2. Which of the following is the correct syntax to sort a DataFrame df by column 'age' in ascending order?
easy
A. df.sort('age', ascending=True)
B. df.sort_values('age', ascending=True)
C. df.sort_values(by='age', ascending=True)
D. df.sort_values(by='age', ascending=False)
Solution
Step 1: Recall the correct pandas sorting method
The correct method to sort a DataFrame by column is sort_values() with the parameter by='column_name'.
Step 2: Check the ascending parameter and syntax
To sort ascending, use ascending=True. df.sort_values(by='age', ascending=True) uses the correct method and parameters.
Final Answer:
df.sort_values(by='age', ascending=True) -> Option C
Quick Check:
sort_values(by=col, ascending=True) is correct [OK]
Hint: Use sort_values(by=col, ascending=True) for ascending sort [OK]
Rows sorted by score from highest to lowest -> Option A
Quick Check:
ascending=False sorts descending [OK]
Hint: False sorts descending, highest first [OK]
Common Mistakes:
Thinking ascending=False sorts ascending
Confusing sorting by name vs score
Expecting an error from ascending=False
4. What is wrong with this code snippet?
df.sort_values(by='height', ascending='False')
medium
A. sort_values does not accept ascending parameter
B. The column name must be a list, not a string
C. No error, code is correct
D. ascending should be a boolean, not a string
Solution
Step 1: Check the type of ascending parameter
The ascending parameter expects a boolean value: True or False, not a string.
Step 2: Identify the error in the code
Here, ascending='False' is a string, which will cause unexpected behavior or error.
Final Answer:
ascending should be a boolean, not a string -> Option D
Quick Check:
ascending must be True/False boolean [OK]
Hint: Use True/False without quotes for ascending [OK]
Common Mistakes:
Passing 'False' as string instead of boolean
Thinking column name must be list always
Assuming no error with wrong ascending type
5. You have a DataFrame df with columns 'city' and 'temperature'. You want to sort it first by 'city' alphabetically ascending, then by 'temperature' descending. Which code does this correctly?
hard
A. df.sort_values(by=['city', 'temperature'], ascending=False)
B. df.sort_values(by=['city', 'temperature'], ascending=[True, False])
C. df.sort_values(by=['temperature', 'city'], ascending=[False, True])
D. df.sort_values(by=['city', 'temperature'], ascending=[False, True])
Solution
Step 1: Understand multi-column sorting
To sort by multiple columns, pass a list to by and a list of booleans to ascending matching each column.
Step 2: Match sorting order to columns
We want 'city' ascending (True) and 'temperature' descending (False), so ascending=[True, False].
Final Answer:
df.sort_values(by=['city', 'temperature'], ascending=[True, False]) -> Option B
Quick Check:
Multi-column sort uses list of booleans [OK]
Hint: Use ascending list matching columns for multi-sort [OK]
Common Mistakes:
Using single boolean for multi-column ascending
Swapping column order in by list
Mixing ascending True/False order
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.