📖 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
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
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
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
Hint
Use print(book_info) to show the selected row.
Practice
(1/5)
1. What does the loc function in pandas primarily do?
easy
A. Deletes rows based on conditions
B. Selects data by row and column positions
C. Sorts the DataFrame by index
D. Selects data by row and column labels
Solution
Step 1: Understand the purpose of loc
loc is designed to select data using labels, not positions.
Step 2: Compare with other selection methods
Unlike iloc which uses positions, loc uses row and column labels.
Final Answer:
Selects data by row and column labels -> Option D
Quick Check:
loc = label-based selection [OK]
Hint: Remember: loc uses labels, iloc uses positions [OK]
Common Mistakes:
Confusing loc with iloc
Thinking loc sorts data
Assuming loc deletes data
2. Which of the following is the correct syntax to select rows with labels 'a' and 'b' and columns 'x' and 'y' using loc?
easy
A. df.loc[a,b][x,y]
B. df.loc[['a', 'b'], ['x', 'y']]
C. df.loc[a:b, x:y]
D. df.loc('a', 'b', 'x', 'y')
Solution
Step 1: Identify correct loc syntax
loc uses square brackets with row labels first, then column labels, both as lists for multiple selections.
Step 2: Check each option
df.loc[['a', 'b'], ['x', 'y']] uses correct list syntax. Options A, B, and C use wrong syntax or parentheses.
Final Answer:
df.loc[['a', 'b'], ['x', 'y']] -> Option B
Quick Check:
Use lists inside loc brackets [OK]
Hint: Use double brackets with lists for rows and columns [OK]
Rows are labeled 'x', 'y', 'z'. Columns are 'A' and 'B'. Value at row 'y' and column 'B' is 50.
Step 2: Apply loc selection
df.loc['y', 'B'] selects the single value at row 'y' and column 'B', which is 50.
Final Answer:
50 -> Option A
Quick Check:
Label 'y' and column 'B' value = 50 [OK]
Hint: Single label loc returns a scalar value [OK]
Common Mistakes:
Expecting a list or Series instead of scalar
Confusing row and column labels
Using iloc syntax instead
4. What is wrong with this code snippet?
df.loc['a':'c', 'x', 'y']
Assuming df has rows labeled 'a' to 'c' and columns 'x' and 'y'.
medium
A. Too many arguments inside loc brackets
B. Row slice labels are invalid
C. Column labels must be integers
D. loc cannot slice rows
Solution
Step 1: Check loc argument structure
loc expects two arguments inside one pair of brackets: rows and columns, separated by a comma.
Step 2: Identify error in code
The code has three arguments inside brackets: 'a':'c', 'x', 'y'. This is invalid syntax.
Final Answer:
Too many arguments inside loc brackets -> Option A
Quick Check:
loc needs exactly two arguments inside brackets [OK]
Hint: Use one comma inside loc brackets for rows and columns [OK]
Common Mistakes:
Passing multiple column labels as separate arguments
Using multiple commas inside loc brackets
Confusing loc with multiple bracket calls
5. You have a DataFrame df with index labels as dates from '2023-01-01' to '2023-01-05' and columns ['temp', 'humidity']. How would you use loc to select all rows from '2023-01-02' to '2023-01-04' and only the 'temp' column as a DataFrame?
hard
A. df.loc[['2023-01-02', '2023-01-04'], 'temp']
B. df.loc['2023-01-02':'2023-01-04', 'temp']
C. df.loc['2023-01-02':'2023-01-04', ['temp']]
D. df.loc['temp', '2023-01-02':'2023-01-04']
Solution
Step 1: Understand row and column selection
Rows are date labels; we want a slice from '2023-01-02' to '2023-01-04'. Columns are selected by label; we want only 'temp'.
Step 2: Use loc with slice and list
Row slice is a string slice, column selection needs a list for one or more columns. So use ['temp'] for columns.
Final Answer:
df.loc['2023-01-02':'2023-01-04', ['temp']] -> Option C
Quick Check:
Slice rows by labels, columns as list [OK]
Hint: Use slice for rows and list for columns in loc [OK]
Common Mistakes:
Using single string for multiple columns
Swapping rows and columns in loc
Using list for row slice instead of slice
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.