Q:

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

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to check whether a Pandas DataFrame is empty?... >>
<< Count the frequency that a value occurs in a DataF...