Pandas.DataFrame.iloc in Python

In this article, we will study Pandas.DataFrame.iloc in Python.

Let us create DataFrame. For this, we first need to import Pandas. Pandas is an open source Python library. It allows us to create and manipulate data. Look at the following code:

import pandas as pd

employee_data = {"Name":["Vish","Sahil","Priya","Anjali","Prakash","Rahul"],
                      "Age" :[24,23,45,35,30,29],
                      "Salary":[89000,80000,79000,60000,92000,67000]}

df = pd.DataFrame(employee_data)

print(df)

OUTPUT

Name
Age
Salary
0
Vish
24
89000
1
Sahil
23
80000
2
Priya
45
79000
3
Anjali
35
60000
4
Prakash
30
92000
5
Rahul
29
67000

We will perform all operations on this DataFrame.

Program: Pandas.DataFrame.iloc in Python

Let us now understand Pandas.DataFrame.iloc in Python.

Pandas.DataFrame.iloc is used for selecting an element by its position. It is used to select and index rows and columns from DataFrames. iloc selects the data by index of rows or columns. In iloc, we can pass two arguments: row number and column number.

Let us understand this using an example. Look at the following code:

df.iloc[0]

OUTPUT

Name       Vish
Age          24
Salary    89000
Name: 0, dtype: object

In this example, we have passed “0” which means 0th row. Hence, data from 0th row is displayed.

Let’s take another example. Look at the following code:

df.iloc[0:3]

OUTPUT

Name
Age
Salary
0
Vish
24
89000
1
Sahil
23
80000
2
Priya
45
79000

In this example, “0:3” means 0 to 2 rows. Hence, data from 0 to 2 rows is displayed.

Let’s take another example. Look at the following code:

df.iloc[-1]

OUTPUT

Name      Rahul
Age          29
Salary    67000
Name: 5, dtype: object

In this example, “-1” means the last row. Hence, data from the last row is displayed.

Let’s take another example. Look at the following code:

df.iloc[:,2]

OUTPUT

0    89000
1    80000
2    79000
3    60000
4    92000
5    67000
Name: Salary, dtype: int64

In this example, “:” means all rows and “2” means 2nd column. Since, indexing here starts from 0, 2nd column is actually “Salary”.

Let’s take another example. Look at the following code:

df.iloc[:,-3]

OUTPUT

0       Vish
1      Sahil
2      Priya
3     Anjali
4    Prakash
5      Rahul
Name: Name, dtype: object

In this example, “:” means all rows and “-3” means last third column. Hence, data of all rows from last third column is displayed.

Let’s take another example. Look at the following code:

df.iloc[[2,5],[0,2]]

OUTPUT

Name
Salary
2
Priya
79000
5
Rahul
67000

In this example, [2,5] means rows with index number 2 and 5 and [0,2] means columns with index number 0 and 2. Hence, data from respective rows and columns is displayed.

In this way, iloc helps in displaying data from the DataFrame using their position.

Thank You.

You may also read: How to Filter rows of DataFrame in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *