A Guide to loc and iloc in Python
How to Select and Filter Data in Python
Pandas, a powerful data manipulation library in Python, provides two essential methods for accessing and manipulating data: loc and iloc. In this guide, we'll explore the functionalities of these methods and showcase how they can be used to extract and manipulate data from a DataFrame. To illustrate the concepts, we'll use a basic example dataset.

Section 1: Introduction to the Example Dataset
import pandas as pd
# Creating a basic example dataset
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'Age': [25, 30, 22, 35, 28],
'Salary': [50000, 60000, 45000, 70000, 55000]
}
df = pd.DataFrame(data)
print(df)
Section 2: Using loc for Label-Based Indexing
2.1 Selecting Rows by Label
# Selecting a specific row by label
row_bob = df.loc[df['Name'] == 'Bob']
print(row_bob)
2.2 Selecting Rows and Columns by Label
# Selecting specific rows and columns by label
subset = df.loc[df['Age'] > 25, ['Name', 'Salary']]
print(subset)
Section 3: Using iloc for Position-Based Indexing
3.1 Selecting Rows by Index
# Selecting a specific row by index
row_index_2 = df.iloc[2]
print(row_index_2)
3.2 Selecting Rows and Columns by Index
# Selecting specific rows and columns by index
subset_index = df.iloc[1:4, [0, 2]]
print(subset_index)
Section 4: Combining loc and iloc for Advanced Selection
# Combining loc and iloc for advanced selection
advanced_selection = df.loc[df['Age'] > 25].iloc[:, 1:]
print(advanced_selection)
Conclusion:
Understanding the nuances of loc and iloc in Pandas is crucial for effective data manipulation. While loc provides label-based indexing for both rows and columns, iloc offers position-based indexing. By mastering these methods, you gain the flexibility to precisely select and manipulate data in your DataFrame. Whether you're dealing with labeled or positional indexing, Pandas' loc and iloc make it easy to extract the information you need. So, dive into the world of Pandas indexing and unleash the full potential of your data manipulation tasks.
Python Fundamentals
Thank you for your time and interest! 🚀 You can find even more content at Python Fundamentals 💫






