We can select rows or columns from a DataFrame using loc[] or iloc[] in pandas. loc[] selects rows or columns from a DataFrame using its labels. And iloc[] selects rows or columns from a DataFrame by using the indexes of the rows or columns. In this article, we will discuss how to select rows of a DataFrame using loc[] and iloc[] in pandas.
Let’s look at an example first.
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)
df2 = df1.loc[["Row 1", "Row 2"]]
df3 = df1.iloc[[0, 1]]
print("df2: \n", df2)
print("df3: \n", df3)
Here, we are first creating a DataFrame df1 from a Python list list1. So, if we print df1, it will look like the following:
Column 1 Column 2 Column 3
Row 1 1 2 3
Row 2 4 5 6
Row 3 7 8 9
The DataFrame has three rows and three columns. And all the rows and columns …








































0 Comments