that we are selecting row 1 to row 3 and column 1. df1.iloc[0:3, 0] indicates we are selecting rows with indexes from 0 to 2 (both inclusive) and column index 0. And as we discussed, loc[] selects rows and columns using the labels, where iloc[] selects rows and columns from a DataFrame by using the indexes of the rows and columns.
So, the output of the above program will be like the following:
Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9 s1: Row 1 1 Row 2 4 Row 3 7 Name: Column 1, dtype: int64 Type of s1: <class 'pandas.core.series.Series'> s2: Row 1 1 Row 2 4 Row 3 7 Name: Column 1, dtype: int64 Type of s2: <class 'pandas.core.series.Series'>
Please also note that both df1.loc[“Row 1″:”Row 3”, “Column 1”] and df1.iloc[0:3, 0] return pandas Series.
We can use similar program to select a single row and multiple columns of a DataFrame using Python. I will leave it to the reader to try out the same.
How to select multiple rows and multiple columns from a DataFrame using pandas?
We can use the following Python code to select multiple rows and multiple columns of a DataFrame using Python.
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”] selects the rows Row 1, Row 2, and Row 3, and the columns Column 1 and …






0 Comments