0
0
Pandasdata~30 mins

sort_values() by multiple columns in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting Data with pandas using sort_values() by multiple columns
📖 Scenario: You work in a small bookstore. You have a list of books with their title, author, and year published. You want to organize this list so that books are sorted first by author name alphabetically, and then by year published from oldest to newest.
🎯 Goal: Build a pandas DataFrame with book data and sort it by author and year using sort_values() with multiple columns.
📋 What You'll Learn
Create a pandas DataFrame called books with columns title, author, and year using the exact data provided.
Create a list called sort_columns with the column names 'author' and 'year' in that order.
Use sort_values() on the books DataFrame with the by parameter set to sort_columns.
Print the sorted DataFrame.
💡 Why This Matters
🌍 Real World
Sorting data by multiple columns is common when organizing records like books, sales, or customer data to find patterns or prepare reports.
💼 Career
Data analysts and scientists often sort data by multiple criteria to clean, explore, and present data clearly.
Progress0 / 4 steps
1
Create the books DataFrame
Import pandas as pd and create a DataFrame called books with these exact entries: title as ['The Hobbit', '1984', 'Brave New World', 'The Catcher in the Rye', 'Animal Farm'], author as ['Tolkien', 'Orwell', 'Huxley', 'Salinger', 'Orwell'], and year as [1937, 1949, 1932, 1951, 1945].
Pandas
Need a hint?

Use pd.DataFrame() with a dictionary where keys are column names and values are lists of data.

2
Create the list of columns to sort by
Create a list called sort_columns with the exact values 'author' and 'year' in that order.
Pandas
Need a hint?

Use square brackets to create a list with the two column names as strings.

3
Sort the DataFrame by multiple columns
Use the sort_values() method on the books DataFrame with the by parameter set to the list sort_columns. Assign the sorted DataFrame back to books.
Pandas
Need a hint?

Use books.sort_values(by=sort_columns) and assign it back to books.

4
Print the sorted DataFrame
Write a print statement to display the sorted books DataFrame.
Pandas
Need a hint?

Use print(books) to show the sorted DataFrame.