📖 Scenario: You work in a small shop and keep track of daily sales in a table. You want to learn how to pick data from this table using two different methods: loc and iloc.
🎯 Goal: Learn how to select rows and columns from a pandas DataFrame using loc (label-based) and iloc (position-based) to understand their differences.
📋 What You'll Learn
Create a pandas DataFrame with specific sales data
Create a variable to select a specific row label
Use loc to select data by label
Use iloc to select data by position
Print the selected data to compare results
💡 Why This Matters
🌍 Real World
In real life, data tables often have labels like dates or names. Knowing how to pick data by label or by position helps you get exactly what you want.
💼 Career
Data scientists and analysts frequently use <code>loc</code> and <code>iloc</code> to filter and select data efficiently for analysis and reporting.
Progress0 / 4 steps
1
Create the sales DataFrame
Create a pandas DataFrame called sales with these exact data: rows labeled "Mon", "Tue", "Wed", columns "apples" and "oranges", and values: Mon: 3, 2; Tue: 5, 1; Wed: 2, 4.
Pandas
Hint
Use pd.DataFrame with a dictionary for columns and index for row labels.
2
Set the row label to select
Create a variable called day_label and set it to the string "Tue" to select Tuesday's sales by label.
Pandas
Hint
Just assign the string "Tue" to day_label.
3
Select Tuesday's sales using loc and iloc
Use loc with day_label to select Tuesday's sales by label and save it in sales_loc. Use iloc with the integer 1 to select Tuesday's sales by position and save it in sales_iloc.
Pandas
Hint
Use sales.loc[day_label] and sales.iloc[1] to select the row.
4
Print the selected sales data
Print sales_loc and sales_iloc to see the sales for Tuesday selected by label and by position.
Pandas
Hint
Use two print() statements, one for each variable.
Practice
(1/5)
1. What is the main difference between loc and iloc in pandas?
easy
A. loc uses labels, iloc uses integer positions
B. loc uses integer positions, iloc uses labels
C. loc selects columns only, iloc selects rows only
D. loc is faster than iloc
Solution
Step 1: Understand loc selection method
loc selects data by row and column labels, meaning it uses the actual names of rows and columns.
Step 2: Understand iloc selection method
iloc selects data by integer positions, starting from 0, ignoring labels.
Final Answer:
loc uses labels, iloc uses integer positions -> Option A
Quick Check:
loc = labels, iloc = positions [OK]
Hint: Remember: loc = labels, iloc = integer positions [OK]
Common Mistakes:
Confusing labels with positions
Thinking loc uses positions
Assuming iloc uses labels
2. Which of the following is the correct syntax to select rows with labels 'a' to 'c' and columns 'x' to 'z' using loc?
easy
A. df.loc['a':'c', 'x':'z']
B. df.iloc['a':'c', 'x':'z']
C. df.loc[0:2, 0:2]
D. df.iloc[0:2, 'x':'z']
Solution
Step 1: Identify loc syntax
loc uses labels, so slicing with labels like 'a':'c' and 'x':'z' is valid.
Step 2: Check other options
Selections using iloc with label slices are invalid because iloc requires integer positions. Using integer slices with loc is incorrect when the labels are strings like 'a', 'c', etc.
Final Answer:
df.loc['a':'c', 'x':'z'] -> Option A
Quick Check:
loc uses labels in slices [OK]
Hint: Use labels inside loc brackets, positions inside iloc [OK]
Common Mistakes:
Using integer positions with loc
Using labels with iloc
Mixing loc and iloc syntax
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A':[10,20,30], 'B':[40,50,60]}, index=['x','y','z'])
What is the output of df.iloc[1, 0]?
medium
A. 30
B. 40
C. 50
D. 20
Solution
Step 1: Understand DataFrame structure
Rows are labeled 'x','y','z' with values in column 'A' as [10,20,30]. Positions start at 0, so row 1 is 'y', column 0 is 'A'.
Step 2: Apply iloc selection
df.iloc[1, 0] selects row at position 1 ('y') and column at position 0 ('A'), value is 20.
Final Answer:
20 -> Option D
Quick Check:
iloc uses positions: row 1, col 0 = 20 [OK]
Hint: iloc uses zero-based positions, count rows and columns from 0 [OK]
Common Mistakes:
Using labels instead of positions
Confusing row and column indices
Selecting wrong cell by mixing loc and iloc
4. Consider this code:
import pandas as pd
df = pd.DataFrame({'A':[1,2,3]}, index=[10,20,30])
print(df.loc[1])
What error will occur and why?
medium
A. No error, prints 2
B. KeyError because label 1 does not exist in index
C. IndexError because position 1 is out of range
D. TypeError because loc expects string labels
Solution
Step 1: Check DataFrame index labels
Index labels are [10, 20, 30], so label 1 is not present.
Step 2: Understand loc behavior
loc looks for label 1, which does not exist, causing a KeyError.
Final Answer:
KeyError because label 1 does not exist in index -> Option B
Quick Check:
loc needs existing labels, else KeyError [OK]
Hint: loc needs exact labels; missing label causes KeyError [OK]
Common Mistakes:
Thinking loc uses positions
Expecting no error when label missing
Confusing KeyError with IndexError
5. You have a DataFrame with non-numeric row labels: