Python iloc() function
The iloc() function is an indexed-based selecting method which means that we have to pass an integer index in the method to select a specific row/column. This method does not include the last element of the range passed in it unlike loc(). iloc() does not accept the boolean data unlike loc(). Operations performed using iloc() are:
Example 1: Selecting Rows Using Integer Indices
In this example, the code employs the iloc
function to extract and display specific rows with indices 0, 2, 4, and 7 from the DataFrame, showcasing information about selected cars in the dataset.
python3
# selecting 0th, 2nd, 4th, and 7th index rows display(data.iloc[[ 0 , 2 , 4 , 7 ]]) |
Output
Brand Year Kms Driven City Mileage
0 Maruti 2012 50000 Gurgaon 28
2 Tata 2011 60000 Mumbai 25
4 Maruti 2012 10000 Mumbai 28
7 Tata 2018 15000 Chennai 21
Example 2: Selecting a Range of Columns and Rows Simultaneously
In this example, the code utilizes the iloc
function to extract and display a subset of the DataFrame, including rows 1 to 4 and columns 2 to 4. This provides information about a specific range of cars and their relevant attributes in the dataset.
python3
# selecting rows from 1 to 4 and columns from 2 to 4 display(data.iloc[ 1 : 5 , 2 : 5 ]) |
Output
Kms Driven City Mileage
1 30000 Delhi 27
2 60000 Mumbai 25
3 25000 Delhi 26
4 10000 Mumbai 28
Difference between loc() and iloc() in Pandas DataFrame
Pandas library of Python is very useful for the manipulation of mathematical data and is widely used in the field of machine learning. It comprises many methods for its proper functioning. loc() and iloc() are one of those methods. These are used in slicing data from the Pandas DataFrame. They help in the convenient selection of data from the DataFrame in Python. They are used in filtering the data according to some conditions.