ADVERTISEMENT
ADVERTISEMENT

Python Pandas: Get index of rows which column matches certain value

Given a DataFrame, we have to get the index of rows which column matches certain value.
Submitted by Pranit Sharma, on April 29, 2022

DataFrame rows are based on the index values. We can manipulate both rows and columns in pandas. On the other hand, index are the integer values representing the number of rows and columns separately. We can perform many operations on rows of a DataFrame on the basis of a specific condition. Here, we are going to find the index of rows whose column matches a certain value.

Following is the syntax for achieving this task:

Syntax:

DataFrame.index[df['column_name']=='particular_value'].tolist()

Here, the above syntax will return a list of indices of rows whose column matches the specific condition passed inside the DataFrame.index() method.

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# Importing pandas package
import pandas as pd

# Creating a dictionary
dict = {
    'Name':['Harry','Raman','Parth','Mukesh','Neelam','Megha','Deepak','Nitin','Manoj','Rishi','Sandeep','Divyansh','Sheetal','Shalini'],
    'Sport_selected':['Cricket','Cricket','Cricket','Cricket','Basketball','Basketball','Football','Cricket','Tennis','Tennis','Chess','Football','Basketball','Chess']
}

# Creating a DataFrame
df=pd.DataFrame(dict)

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

# Generating a list if all the indices of rows 
# whose column value matches a condition
indices_list = df.index[df['Sport_selected']=='Cricket'].tolist()

# Display list of indices
print("Indices or rows where Sport_selected is cricket are:",indices_list)

Output:

Output | Python Pandas: Get index of rows

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.