How to Locate Rows and Columns Using loc, iloc in Python
Share
Condition for Using loc and iloc in Python
Description:
In Pandas, loc and iloc are used to locate or select rows and columns in a DataFrame.
These functions are widely used for indexing and retrieving data based on either labels (loc)
or integer positions (iloc).
loc: Used for label-based indexing. You can select rows and columns by their labels (index names or column names). iloc: Used for integer-based indexing. You select rows and columns by their positions (integer indices).
Step-by-Step Process
Import Pandas: Import the Pandas library with import pandas as pd.
Create or Load a DataFrame: Create a DataFrame manually or load it from a file.
Using loc: Use df.loc[row_label, column_label] to access a specific cell or slice rows/columns by label.
Using iloc: Use df.iloc[row_position, col_position] to access specific rows and columns using integer positions.
Sample Source Code
# Code for Locating Rows and Columns Using loc and iloc
# Access the row where Name is 'Alice'
print("\nUsing loc to access the row where Name is 'Alice':")
print(df.loc[df['Name'] == 'Alice'])
# Access specific row and column (row label = 2, column label = 'Age')
print("\nUsing loc to access specific row and column (index 2, 'Age'):")
print(df.loc[2, 'Age'])
# Select a range of rows (from index 1 to 3) and columns (from 'Name' to 'Salary')
print("\nUsing loc to select a range of rows and columns:")
print(df.loc[1:3, 'Name':'Salary'])
# Using iloc (Integer-based indexing)
# Access the row at position 1 (second row)
print("\nUsing iloc to access the row at position 1:")
print(df.iloc[1])
# Access the element at row position 2 and column position 1 ('Age' is the second column)
print("\nUsing iloc to access the element at row position 2 and column position 1:")
print(df.iloc[2, 1])
# Select a range of rows (from position 0 to 3) and columns (from position 0 to 2)
print("\nUsing iloc to select a range of rows and columns:")
print(df.iloc[0:3, 0:2])