0
0
Pandasdata~30 mins

sort_index() for index sorting in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Sort DataFrame by Index Using sort_index()
📖 Scenario: You work in a small bookstore. You have a list of books with their prices, but the list is not sorted by the book titles. You want to organize your list alphabetically by the book titles to find books faster.
🎯 Goal: Create a pandas DataFrame with book titles as the index and prices as the values. Then, sort the DataFrame by the index (book titles) using sort_index().
📋 What You'll Learn
Create a pandas DataFrame called books with the exact index labels: 'Python Basics', 'Data Science', 'Machine Learning', and 'Deep Learning'.
The DataFrame must have a single column named Price with the exact values: 25, 40, 55, and 60 respectively.
Create a variable called sorted_books that contains the DataFrame sorted by its index using sort_index().
💡 Why This Matters
🌍 Real World
Sorting data by index helps organize information alphabetically or by date, making it easier to find and analyze data quickly.
💼 Career
Data analysts and scientists often need to sort data tables to prepare reports or perform analysis efficiently.
Progress0 / 4 steps
1
Create the initial DataFrame
Import pandas as pd and create a DataFrame called books with the index labels 'Python Basics', 'Data Science', 'Machine Learning', and 'Deep Learning'. The DataFrame should have one column named Price with values 25, 40, 55, and 60 respectively.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary for the column and specify the index parameter for the row labels.

2
Add a variable for sorted DataFrame
Create a variable called sorted_books and assign it the value of books sorted by its index using the sort_index() method.
Pandas
Need a hint?

Use books.sort_index() and assign it to sorted_books.

3
Sort the DataFrame by index in descending order
Modify the sorted_books variable to sort the books DataFrame by its index in descending order by passing the argument ascending=False to sort_index().
Pandas
Need a hint?

Use the ascending=False argument inside sort_index() to sort in descending order.

4
Reset the index after sorting
Reset the index of sorted_books using the reset_index() method and assign the result back to sorted_books. This will move the index labels into a column.
Pandas
Need a hint?

Use reset_index() on sorted_books and assign it back to sorted_books.