How are loc and iloc Different in Pandas?

The loc and iloc methods are used for accessing rows and columns in Pandas DataFrames. In this short how-to article, we will learn how these two methods are different.

loc_and_iloc_Different_in_Pandas

Pandas

Rows and columns have both an index and a label. The difference between the loc and iloc methods are related to how they access rows and columns.

  • The loc method uses label
  • The iloc method uses index
				
					# Second column with loc
df.loc[:, "f2"]

# Second column with iloc
df.iloc[:, 1]
				
			

The value before the comma indicates rows to be selected and the one after the comma is for columns. The colon means selecting all.

We can also select particular row and column combinations with these methods.

				
					# Select first row and second column with loc
df.loc[0, "f2"]

# Select first row and second column with iloc
df.iloc[0, 1]
				
			

You may have noticed that the index and the label are the same for a row. The reason is that Pandas assigns integer labels to rows unless the labels are explicitly defined.

Both loc and iloc methods can be used to extract a range of row and column combinations.

				
					# Select first two rows and first two columns with loc
df.loc[:1, ["f1", "f2"]]

# Select first two rows and first two columns with iloc
df.iloc[:2, :2]
				
			

This question is also being asked as:

  • Pandas iloc returns different range than loc

People have also asked for:

You may also like

Start Monitoring Your Models in Minutes