0
0
Pandasdata~15 mins

loc for label-based selection in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using loc for Label-Based Selection in pandas
📖 Scenario: You work in a small bookstore. You have a list of books with their prices and stock counts. You want to find specific books by their titles and see their details.
🎯 Goal: Learn how to use loc in pandas to select rows and columns by labels.
📋 What You'll Learn
Create a pandas DataFrame with book data
Create a variable with a book title to select
Use loc to select the row for that book
Print the selected row
💡 Why This Matters
🌍 Real World
Selecting data by labels is common when working with real datasets like sales records, inventory lists, or customer information.
💼 Career
Data analysts and scientists often use label-based selection to quickly access and analyze specific rows in large datasets.
Progress0 / 4 steps
1
Create the books DataFrame
Create a pandas DataFrame called books with these exact data: titles as index 'The Hobbit', '1984', 'Python 101'; columns 'Price' with values 15.99, 12.50, 29.99; and 'Stock' with values 5, 8, 3.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary for columns and set index to the list of titles.

2
Create a variable for the book title
Create a variable called selected_book and set it to the string '1984'.
Pandas
Need a hint?

Just assign the string '1984' to the variable selected_book.

3
Select the row for the chosen book using loc
Use loc to select the row from books where the index matches selected_book. Store this row in a variable called book_info.
Pandas
Need a hint?

Use books.loc[selected_book] to get the row by label.

4
Print the selected book information
Print the variable book_info to display the price and stock of the selected book.
Pandas
Need a hint?

Use print(book_info) to show the selected row.