pandas
data manipulation
indexing
loc vs iloc
at vs iat

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.

Practice ML system design

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.
  • loc and at: Will raise KeyError if labels are not found.
  • iloc and iat: Will raise IndexError for invalid indices.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track 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.

Practice ML system design

All Rights Reserved.