Common use cases for the loc operator in pandas include:
-
Selecting Rows by Label: Access specific rows using their index labels.
df.loc['row_label'] -
Selecting Specific Columns: Access specific columns by their names.
df.loc[:, 'column_name'] -
Filtering Rows Based on Conditions: Select rows that meet certain conditions.
df.loc[df['column_name'] > value] -
Selecting a Subset of Rows and Columns: Access a specific subset of the DataFrame.
df.loc[start_label:end_label, ['col1', 'col2']] -
Updating Values: Modify specific values in the DataFrame.
df.loc[df['column_name'] == condition, 'target_column'] = new_value -
Accessing Multiple Rows and Columns: Use lists to select multiple rows and columns.
df.loc[['row1', 'row2'], ['col1', 'col2']] -
Using Boolean Arrays: Select rows based on boolean conditions.
mask = df['column_name'] > value df.loc[mask] -
Setting Values with Conditions: Set values based on a condition.
df.loc[df['column_name'] < value, 'target_column'] = new_value
These use cases demonstrate the versatility of loc for data selection, filtering, and modification in pandas DataFrames.
