The loc function helps you pick rows and columns from a table using their names. It makes finding data easy and clear.
loc for label-based selection in Pandas
df.loc[row_label, column_label]
row_label and column_label can be a single label, a list of labels, or a slice of labels.
If you leave column_label empty, it selects all columns for the given rows.
df.loc['Alice']df.loc['Bob', 'Age']
df.loc['Alice':'Charlie', ['Age', 'Score']]
df.loc[:, 'Score']This code creates a table with names as row labels and two columns: Age and Score. It then shows how to pick data for 'Bob', get Charlie's age, and select a smaller table from Alice to Charlie with both columns.
import pandas as pd # Create a simple DataFrame with labels data = { 'Age': [25, 30, 22, 35], 'Score': [88, 92, 95, 70] } labels = ['Alice', 'Bob', 'Charlie', 'Diana'] df = pd.DataFrame(data, index=labels) # Select row for 'Bob' bob_data = df.loc['Bob'] # Select 'Age' for 'Charlie' charlie_age = df.loc['Charlie', 'Age'] # Select rows from 'Alice' to 'Charlie' and columns 'Age' and 'Score' subset = df.loc['Alice':'Charlie', ['Age', 'Score']] print("Bob's data:") print(bob_data) print("\nCharlie's Age:") print(charlie_age) print("\nSubset of data:") print(subset)
Using loc includes the last label in slices (unlike normal Python slices).
If a label does not exist, loc will raise an error.
You can use boolean arrays with loc to filter rows by conditions.
loc selects data by row and column labels.
It works with single labels, lists, or slices of labels.
It is useful for clear and readable data selection in tables.
Practice
loc function in pandas primarily do?Solution
Step 1: Understand the purpose of
loclocis designed to select data using labels, not positions.Step 2: Compare with other selection methods
Unlikeilocwhich uses positions,locuses row and column labels.Final Answer:
Selects data by row and column labels -> Option DQuick Check:
loc = label-based selection [OK]
- Confusing loc with iloc
- Thinking loc sorts data
- Assuming loc deletes data
loc?Solution
Step 1: Identify correct
locsyntaxlocuses 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 BQuick Check:
Use lists inside loc brackets [OK]
- Using parentheses instead of brackets
- Not using lists for multiple labels
- Mixing label slices without quotes
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.loc['y', 'B']?Solution
Step 1: Understand the DataFrame structure
Rows are labeled 'x', 'y', 'z'. Columns are 'A' and 'B'. Value at row 'y' and column 'B' is 50.Step 2: Apply
locselectiondf.loc['y', 'B']selects the single value at row 'y' and column 'B', which is 50.Final Answer:
50 -> Option AQuick Check:
Label 'y' and column 'B' value = 50 [OK]
- Expecting a list or Series instead of scalar
- Confusing row and column labels
- Using iloc syntax instead
df.loc['a':'c', 'x', 'y']
Assuming
df has rows labeled 'a' to 'c' and columns 'x' and 'y'.Solution
Step 1: Check
locargument structurelocexpects 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 AQuick Check:
loc needs exactly two arguments inside brackets [OK]
- Passing multiple column labels as separate arguments
- Using multiple commas inside loc brackets
- Confusing loc with multiple bracket calls
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?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
Row slice is a string slice, column selection needs a list for one or more columns. So uselocwith slice and list['temp']for columns.Final Answer:
df.loc['2023-01-02':'2023-01-04', ['temp']] -> Option CQuick Check:
Slice rows by labels, columns as list [OK]
- Using single string for multiple columns
- Swapping rows and columns in loc
- Using list for row slice instead of slice
Ready to prove it?
Pass the test and this pattern moves unknown
