W3docs

How are iloc and loc different?

iloc and loc are both used to select rows and columns from a Pandas DataFrame, but they work differently.

iloc and loc are both used to select rows and columns from a Pandas DataFrame, but they work differently.

iloc uses integer-based indexing, so you use integers to select rows and columns. For example:

Pandas iloc method usage sample

python— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This will select the first and second rows and the first column of the DataFrame, resulting in the following output:


A
0  1
1  2

loc uses label-based indexing, so you use the labels of the rows and columns to select data. For example:

Pandas loc method usage sample

python— editable, runs on the server

This will select the rows with labels 'a' and 'b' and the column with label 'A' of the DataFrame, resulting in the following output:


A
a  1
b  2

In summary, iloc uses integer-based indexing and loc uses label-based indexing to select rows and columns from a DataFrame.