Both loc() and iloc() methods are used for slicing the data from the pandas DataFrame. Both of these methods are effective and efficient ways of selecting rows or columns. Also, these methods require some kind of condition as a parameter based on which it filters out the data from the DataFrame.
Let us understand the example given below:
Output:
In the above example, we have created a DataFrame. Now we will use the loc() and iloc() methods and observer the difference between them.
Using loc() Method
The loc() method is a type of data selection method which takes the name of a row or column as a parameter. To perform various operations using the loc() method, we need to pass the required condition of rows and columns to get the filtered data.
Output:
Here, the loc() method returns the entire row where marks of 'Harry' and 'Peter' are 66 and 70 respectively. In this way, loc() method works upon a particular condition.
Using iloc() Method
The 'i' in iloc() stands for index. This is also a data selection method but here, we need to pass the proper index as a parameter to select the required row or column. Index are nothing but the integer value ranging from 0 to n-1 which represents the number of rows or columns. We can perform various operations using iloc() method. Inside iloc() method, the index value of the row comes first followed by the number of columns.
Output:
Here, first, we have passed a list of indices which means all those rows which we want to be displayed, and second time, we have passed the sliced index without any list, which means we want the rows from 0 to 2 followed by the columns number 1.
Note: The slicing method does not consider the end value i.e., the value specified after the colon (:).
need an explanation for this answer? contact us directly to get an explanation for this answer