Extract single and multiple rows using pandas.DataFrame.iloc in Python

In this tutorial, we will learn how to extract single and multiple rows from a Pandas DataFrame in Python.

First of all, we need to import the Pandas library to convert our data in DataFrame object.

See the code below before we go forward:

import pandas as pd

Data = [{'a': 12 , 'b':45, 'c':36 , 'd': 45},
        {'a': 100 , 'b':450, 'c':360 , 'd': 450},
        {'a': 1000 , 'b':5000, 'c':3600 , 'd': 4500},
        {'a': 12000 , 'b':45000, 'c':36000 , 'd': 45000}]

final_data = pd.DataFrame(Data)

print(type(final_data))

print(final_data)

We store the data in Data variable then we convert it in DataFrame object and stored it in final_data.

The output will be:

class 'pandas.core.frame.DataFrame'> 

        a	b	c	d
0	12	45	36	45
1	100	450	360	450
2	1000	5000	3600	4500
3	12000	45000	36000	45000

To extract rows and column from dataset we have iloc[rows, columns] method, where first argument is row_index and second argument is column_index of dataset.

Output:

Case 1:

print(final_data.iloc[1])
a    100
b    450
c    360
d    450

Name: 1, dtype: int64

Case 2:
print(final_data.iloc[0,2])

36

Suppose, we want to extract one row then we need to specify only row index, by default column_index is select as all (we represent all as colon ‘:’ ) and in Python indexing of row and column starts from 0 so our first row is 0 index and next row is index 1 and so on.

So in case 1: we get all values of row 1, we can also write iloc[1,:] instead of iloc[1].

In case 2: we get single element because we want the value of 0th row and 2nd column which is 36.

Output

case 3:

print(final_data.iloc[0:2,:])

     a    b    c    d
0   12   45   36   45
1  100  450  360  450

case 4:
print(final_data.iloc[0:2, 1:2])

     b
0   45
1  450

case 5:
print(final_data.iloc[[2,3],[1,2]])

       b      c
2   5000   3600
3  45000  36000

case 6:
print(final_data.iloc[[0,2,3]])

       a      b      c      d
0     12     45     36     45
2   1000   5000   3600   4500
3  12000  45000  36000  45000

We can also do index slicing in iloc as in case 3: we slice row value from 0:2 ( 0:2 represents [0,2) ), it is important to know in index slicing.

If we want to extract only particular rows and column we can give argument as list of required row and columns as in case 5 and case 6.

I hope you enjoyed.

Also read:

Leave a Reply

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