We often get confused between loc[] and iloc[] in Python pandas. What is the difference between loc[] and iloc[] in pandas? In this article, we will explore that.
In Python pandas, both loc[] and iloc[] are used to select rows and/or columns from a DataFrame. The main difference between loc[] and iloc[] is that loc[] selects rows and/or columns using the labels of the rows and columns. And iloc[] selects rows and/or columns using the indexes of the rows and columns.
Let’s look at some examples to understand this better.
import pandas list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] df1 = pandas.DataFrame(list1, index=["Row 1", "Row 2", "Row 3"], columns=["Column 1", "Column 2", "Column 3"]) print(df1) series1 = df1.loc["Row 1"] series2 = df1.iloc[0] print("series1: \n", series1) print("series2: \n", series2)
Here, both loc[] and iloc[] are selecting the first row. loc[] selects the row using its label “Row 1” and iloc[] selects the row using its index, i.e., 0. Please note that both loc[] and iloc[] here select a row and they return pandas Series.
The output of the above program will be:






0 Comments