Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9
Now, we are using loc[] to select data from row 1 and column 1. Then, we are using iloc[] to select the same data from row 1 and column 1. Please note that the difference between loc[] and iloc[] is that loc[] selects data from a DataFrame by using its labels. And iloc[] selects data from a DataFrame by using the indexes of rows and columns. So, here df1.loc[“Row 1”, “Column 1”] and df1.iloc[0, 0] will select the same data.
So, the output of the given program will be:
Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9 n1: 1 Type of n1: <class 'numpy.int64'> n2: 1 Type of n2: <class 'numpy.int64'>
Please note that here loc[] and iloc[] return integers.
How to select multiple rows and a single column from a DataFrame using pandas?
Now, in this example, we will use loc[] and iloc[] to select multiple rows and a single column of 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) s1 = df1.loc["Row 1":"Row 3", "Column 1"] s2 = df1.iloc[0:3, 0] print("s1: \n", s1) print("Type of s1: ", type(s1)) print("s2: \n", s2) print("Type of s2: ", type(s2))
Here, we are using a slice object (“:”) to select multiple rows. df1.loc[“Row 1″:”Row 3”, “Column 1”] indicates …






0 Comments