Python

pandas | loc, iloc

ivvy07 2024. 1. 4. 23:09

`loc` and `iloc` are two methods in Pandas that are used for accessing data from a DataFrame. They are used to select rows and columns based on labels (`loc`) or integer indices (`iloc`). Here's a brief explanation of the differences:

1. **`loc` (Label-based indexing):**
   - `loc` is primarily label-based indexing, meaning that you specify the row and column labels to access data.
   - It includes the end value in the range (i.e., it is inclusive on both ends).
   - The syntax is `df.loc[row_label, column_label]` or `df.loc[row_label_range, column_label_range]`.

df.loc[2, 'column_name']  # Access a specific element
df.loc[1:3, 'column_name']  # Access a range of rows and a specific column



2. **`iloc` (Integer-based indexing):**
   - `iloc` is primarily integer-location based indexing, meaning that you specify the row and column indices (integer positions) to access data.
   - It does not include the end value in the range (i.e., it is exclusive on the upper end).
   - The syntax is `df.iloc[row_index, column_index]` or `df.iloc[row_index_range, column_index_range]`.

df.iloc[2, 1]  # Access a specific element
df.iloc[1:4, 0:3]  # Access a range of rows and columns using integer indices


In summary:

- Use `loc` when you want to access data based on labels.
- Use `iloc` when you want to access data based on integer indices.

It's important to choose the appropriate method based on your specific use case, whether you are working with labeled data or using numerical indices.