The Ultimate Guide to loc and iloc in Python Pandas

How to Select and Filter Data in Python

Python Programming
5 min readJul 18, 2024

Python pandas library provides several methods for selecting and filtering data, such as loc, iloc, [ ] bracket operator, query, isin, between.

Image from pexels.com

This article will guide you through the essential techniques and functions for data selection and filtering using pandas. Whether you need to extract specific rows or columns or apply conditional filtering, pandas has got you covered. Let’s dive in!

Table of Contents

1. Selecting Columns : [ ] operator, loc, iloc
2. Filtering Rows : [ ] operator, loc, iloc, isin, query, between, string methods
3. Updating Values : loc, iloc, replace

1. Selecting Columns

  • loc[ ] : This accessor selects rows and columns by labels.
    Example: df.loc[row_label, column_label]

*** You can also use loc for slicing operations:
df.loc['row1_label':'row2_label' , 'column1_label':'column2_label']

# Using loc for label-based selection
df.loc[:, 'Customer Country':'Customer State']

--

--