Getting the integer index of a pandas dataframe row fulfilling a condition

Learn, how to get the integer index of a pandas dataframe row fulfilling a condition in Python? By Pranit Sharma Last updated : October 06, 2023

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.

Problem statement

Suppose that we are given a pandas DataFrame where a specific column is used as an index, we need to find the index number where a certain condition is met for example, where we need to find the index where the column value (which is used as an index) is 3.

Getting the integer index of a row fulfilling a condition

For this purpose, we will use index.get_location() which is used to get integer location and it takes a parameter called Key which we will pass as the values corresponding to which we want the index.

Let us understand with the help of an example,

Python program to get the integer index of a pandas dataframe row fulfilling a condition

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame(np.arange(1,7).reshape(2,3),columns = list('ABC'),index=pd.Series([2,3], name='B'))

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# Getting the index where B=3
res = df.index.get_loc(3)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Getting the integer index of a pandas dataframe row fulfilling a condition

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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