How do I find the iloc of a row in pandas dataframe?

Learn, how to find the iloc of a row in pandas dataframe?
Submitted by Pranit Sharma, on November 14, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

iloc of a row in pandas dataframe

i in iloc[] stands for 'index'. This is also a data selection method but here, we need to pass the proper index as a parameter to select the required row or column. Indexes are nothing but integer value ranging from 0 to n-1 which represents the number of rows or columns. We can perform various operations using the pandas.DataFrame.iloc[] property. Inside pandas.DataFrame.iloc[] property, the index value of the row comes first followed by the number of columns.

Problem statement

Suppose, we are given an indexed DataFrame, we can search a row by its index but we need to find the iloc this particular row.

Finding the iloc of a row in pandas dataframe

For this purpose, we will simply find out some indices less than some particular index and find out the last value of this result. These values will act as an object and we will find its name with .name attribute.

Let us understand with the help of an example,

Python program to find the iloc of a row in pandas dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Defining indices
indices = pd.date_range('10/10/2020', periods=8)

# Creating DataFrame
df = pd.DataFrame(pd.DataFrame(np.random.randn(8, 4), index=indices, columns=['A', 'B', 'C', 'D']))

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Finding out the index
res = df[df.index < '2020-10-14'].iloc[-1]

# Display its properties
print("Index:\n",res.name,"\n")

# Display its position in DataFrame
print("Result:\n",df.index.get_loc(res.name))

Output

Example: find the iloc of a row in pandas dataframe

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.