pandas loc vs. iloc vs. at vs. iat?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Understanding Indexing in Pandas: loc, iloc, at, and iat
Pandas, a powerful data manipulation library in Python, provides multiple methods for selecting data, each with its unique features and use cases: loc, iloc, at, and iat. These methods give you the flexibility to access and modify data in DataFrames and Series efficiently, based on either labels or integer locations. Let's dive into each of these methods to understand their usage and differences.
loc: Label-Based Indexing
The loc indexer is label-based, meaning you access data using the row and column labels. It supports boolean arrays, which allow for conditional indexing, and slice operations.
Key Points:
- Syntax:
df.loc[row_labels, column_labels] - Label Based: Access rows and columns by label.
- Multiple Selections: Allows for selecting multiple rows and columns.
Example:
1 Bob Los Angeles 2 Charlie Chicago
- Syntax:
df.iloc[row_indices, column_indices] - Integer Based: Uses zero-based integer indices.
- Slicing Support: Can select ranges of rows and columns.
0 25 New York 1 30 Los Angeles
- Syntax:
df.at[row_label, column_label] - Scalar Access: Quick access to a single element.
- Label Based: Uses labels for access.
- Syntax:
df.iat[row_index, column_index] - Scalar Access: Fast access to individual values.
- Integer Based: Uses integer positions for access.
locandat: Will raiseKeyErrorif labels are not found.ilocandiat: Will raiseIndexErrorfor invalid indices.
Related reading
- Pandas Looking up the list of sheets in an excel file
- pandas merge join two data frames on multiple columns
- Pandas Merging 101
- Pandas Merging 101
- pandas multiple conditions while indexing data frame - unexpected behavior
- Parallel doesnt work with Entity Framework
- Pandas percentage of total with groupby
- Pandas read_csv dtype read all columns but few as string

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.