0
0
Pandasdata~20 mins

loc vs iloc mental model in Pandas - Hands-On Comparison

Choose your learning style9 modes available
Understanding loc vs iloc in pandas
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use two print() statements, one for each variable.