pandas
data manipulation
indexing
loc vs iloc
at vs iat

pandas loc vs. iloc vs. at vs. iat?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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.

Course illustration
Course illustration

All Rights Reserved.