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 uses integer-based indexing, so you use integers to select rows and columns. For example:

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])

Watch a course Python - The Practical Guide

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:

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.