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

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=[0, 1, 2])
print(df.iloc[0:2, 0:1])

<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

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c'])
print(df.loc[['a', 'b'], ['A']])

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.