Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9 series1: Column 1 1 Column 2 2 Column 3 3 Name: Row 1, dtype: int64 series2: Column 1 1 Column 2 2 Column 3 3 Name: Row 1, dtype: int64
In our next example, we will select both rows and columns from a DataFrame.
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) df2 = df1.loc["Row 1":"Row 3", "Column 1":"Column 2"] df3 = df1.iloc[0:3, 0:2] print("df2: \n", df2) print("Type of df2: ", type(df2)) print("df3: \n", df3) print("Type of df3: ", type(df3))
Here, df1.loc[“Row 1″:”Row 3”, “Column 1″:”Column 2”] returns the rows 1, 2, 3, and the columns 1, 2. Please note we are using the labels of the rows and columns to select them using the slice object (“:”).
On the other hand, df1.iloc[0:3, 0:2] returns the rows 0, 1, 2, and the columns 0, 1. But, here we are using the indexes of the rows and columns to select them.
The output of the above program will be:
Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9 df2: Column 1 Column 2 Row 1 1 2 Row 2 4 5 Row 3 7 8 Type of df2:df3: Column 1 Column 2 Row 1 1 2 Row 2 4 5 Row 3 7 8 Type of df3:
Please note that here loc[] and iloc[] select multiple rows and columns and hence, they return pandas DataFrame.






0 Comments