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.

Finding the 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.

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.

For this, 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 code 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 »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.