0
0
Pandasdata~5 mins

loc for label-based selection in Pandas

Choose your learning style9 modes available
Introduction

The loc function helps you pick rows and columns from a table using their names. It makes finding data easy and clear.

You want to get data for a specific person by their name in a table.
You need to select rows between two dates labeled in your data.
You want to pick certain columns by their names to analyze.
You want to update values in a table for a specific label.
You want to filter data using labels instead of numbers.
Syntax
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.

Examples
Selects the row with label 'Alice' and all columns.
Pandas
df.loc['Alice']
Selects the value in the row labeled 'Bob' and the column 'Age'.
Pandas
df.loc['Bob', 'Age']
Selects rows from 'Alice' to 'Charlie' and only the columns 'Age' and 'Score'.
Pandas
df.loc['Alice':'Charlie', ['Age', 'Score']]
Selects the entire 'Score' column for all rows.
Pandas
df.loc[:, 'Score']
Sample Program

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.

Pandas
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)
OutputSuccess
Important Notes

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.

Summary

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.