Python iloc() function – Complete Guide

In this tutorial, you will learn about the Python iloc() function with code examples.

What is Python iloc() function and How It works?

A wide range of modules and functions are available to us in Python for working with data. With the Pandas module, we have more functions to deal with large datasets in general, both in terms of row count and in terms of column count, respectively.

It is possible to select a specific cell of a dataset using the Python iloc() function, that is, to select a value that belongs to a specific row or column from a set of values in a data frame or dataset using the iloc() function in Python.

In this case, we can use the index values assigned to the row and column to retrieve the specific value belonging to that row and column.

Keep in mind that the iloc() function only accepts integer type values as the index values for the values to be accessed and displayed by the function caller.

Syntax:

dataframe.iloc[]

In order to retrieve the records, we are unable to use boolean values as an index. Numeric values must be passed to it in order for it to function properly.

Code Examples For The Python iloc () Function

To demonstrate, we attempted to access all of the data values from every third index in every column in the dataset, as shown in the following illustration.

dataset for Python iloc function
The above dataset is the list of 80 brand names. You can download the dataset here.

Code Example 1: Using read_csv() Function

I will be reading the input dataset that we have above using the pandas library and the read csv() function, and then I will be extracting a specific row of data using the Python iloc() function, which is part of the panda’s package. The following is an example of code that extracts data from a CSV file.

#importing required library
import pandas as pd

#Retrieving the Data using read_csv()
data = pd.read_csv("cereal.csv")

print(data.iloc[5])

Output:

name        Apple Cinnamon Cheerios
mfr                               G
type                              C
calories                        110
protein                           2
fat                               2
sodium                          180
fiber                           1.5
carbo                          10.5
sugars                           10
potass                           70
vitamins                         25
shelf                             1
weight                          1.0
cups                           0.75
rating                    29.509541
Name: 5, dtype: object
Python iloc() function

As you can see in the above code, I was able successfully to extract the specific row data from our dataset using the iloc() function.

Code Example 2: Extracting Number of Row Data Using iloc() Function

In this example, I will use the iloc() function and the panda library’s read_csv() function to extract a number of rows of data from our CSV dataset.

#importing required library
import pandas as pd

#Retrieving the Data using read_csv()
data = pd.read_csv("cereal.csv")

print(data.iloc[6:8])

Output:

          name mfr type  calories  protein  fat  ...  potass  vitamins  shelf  weight  cups     rating
6  Apple Jacks   K    C       110        2    0  ...      30        25      2    1.00  1.00  33.174094
7      Basic 4   G    C       130        3    2  ...     100        25      3    1.33  0.75  37.038562
Extracting Number of Row Data Using iloc() Function

As you can see in the code example above, I was able to extract the specific row data for rows 6 and 7. Similarly, you can retrieve as many rows of data as you want by inserting a colon between the row number and the square box of the iloc() function.

Example 3: Extracting Column Data Using iloc Function

In this example, I’ll show you how to use the iloc function to extract column data from any dataset. For this example, I’ll use a CSV dataset and the pandas’ library’s read csv() function.

#importing required library
import pandas as pd

#Retrieving the Data using read_csv()
data = pd.read_csv("cereal.csv")

print(data.iloc[:,3:5])

Output:

    calories  protein
0         70        4
1        120        3
2         70        4
3         50        4
4        110        2
..       ...      ...
72       110        2
73       110        1
74       100        3
75       100        3
76       110        2

[77 rows x 2 columns]
Extracting Column Data Using iloc Function

For example, as you can see in the code above, columns 3 and 4 were correctly fetched for all of the rows that were used.

Wrap Up

As a result of this article, we now have a better understanding of the Python iloc() function. It can be used to retrieve records from datasets based on the index values.

The iloc() function accepts the concept of an index as a parameter, which allows multiple records to be fetched at the same time. The iloc() takes only integer indexes as parameters, and it does not support floating-point numbers.

I hope this tutorial provided you with a thorough understanding of the Python iloc() function. Please let me know in the comments section if I missed anything; I’d love to include it here.

Further Read:

  1. Iterate Through A List In Python
  2. Exit A Python Program in 3 Ways
  3. How To Find A String In A List In Python
  4. Python 3 Round To 2 Decimal Places: Code Examples

Leave a Comment