Pandas DataFrame ‘iloc’ Keyword.
Table Of Contents:
- Syntax For ‘iloc’ Keyword In Data Frame.
- Examples Of ‘iloc’ Keyword.
(1) Syntax:
pandas.DataFrame.iloc
Description:
Purely integer-location-based indexing for selection by position.
.iloc[]
is primarily integer position based (from0
tolength-1
of the axis), but may also be used with a boolean array.
Allowed inputs are:
An integer, e.g.
5
.A list or array of integers, e.g.
[4, 3, 0]
.A slice object with ints, e.g.
1:7
.A boolean array.
A
callable
function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.A tuple of row and column indexes. The tuple elements consist of one of the above inputs, e.g.
(0, 1)
.
Raises
IndexError
.iloc
will raiseIndexError
if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics).
(2) Examples Of ‘iloc’ Keyword:
Example-1
import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
'Roll_No':[100,101,102,103,104],
'Subject':['Math','English','Science','History','Commerce'],
'Mark':[95,88,76,73,93]}
student_object = pd.DataFrame(student)
student_object
Output:
student_object.iloc[1]
Output:
Name Abhispa
Roll_No 101
Subject English
Mark 88
Name: 1, dtype: object
Note:
- It has fetched the index ‘1’ record, which will be a series.
student_object.iloc[[1,2,3]]
Output:
Note:
- It has fetched the index ‘1’ ,’2′ and ‘3’ records.
- You can specify multiple indexes within an array.
student_object.iloc[1:3]
Output:
Note:
- Here I am specifying a range of indexes from ‘1’ to ‘3’ with ‘:’.
- The actual index will be End Index – 1, which is 3 – 1 = 2.
student_object.iloc[:,'Name':'Subject']
Output:
TypeError Traceback (most recent call last)
Input In [322], in <cell line: 1>()
----> 1 student_object.iloc[:,'Name':'Subject']
TypeError: cannot do positional indexing on Index with these indexers [Name] of type str
Note:
- You can not specify the range of column names as strings in iloc.
- You need to specify the range using integer values.
- The first column starts with the ‘0’ index.
student_object.iloc[1:3,0:3]
Output:
Note:
- You can specify the column and row ranges, Start Column: End Column index.
student_object.iloc[:,0:4]
Output:
student_object.iloc[1,0]
Output:
'Abhispa'
Note:
- Fetching a single value.