Return index label if any condition is met on a column in Pandas Dataframe

Python Methods and Functions

Solution # 1: We can use a simple indexing operation to select all the values ​​in a column that satisfy a given condition.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ 'Date' : [ '10/2 / 2011' , '11/2 / 2011' , ' 12/2 / 2011' , '13/2 / 2011' ],

  'Product' : [ ' Umbrella' , 'Matress' , ' Badminton' , 'Shuttle' ],

'Last_Price' : [ 1200 , 1500 , 1600 , 352 ],

'Updated_Price' : [ 1250 , 1450 , 1550 , 400 ],

' Discount' : [ 10 , 10 , 10 , 10 ]})

 
# Create indexes

df.index = [ 'Item 1' , 'Item 2' , ' Item 3' , 'Item 4' ]

  
# Print the data frame

print (df)

Output:

Now we want to find out the index marks of all elements that have "Update_Price" greater than 1000.

# Select all lines that meet the criteria
# convert the collection of index labels to a list.

Index_label = df [df [ 'Updated Price' ] & gt; 1000 ]. index.tolist ()

 
# Print all labels

print (Index_label)

Output:

As we can see in the output, the above operation has successfully evaluated all values ​​and returned a list containing the index labels.

Solution # 2: We can use Dataframe.query () Pandas Dataframe.query () to select all rows that satisfy some condition for the given column.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ 'Date' : [ ' 10/2 / 2011' , '11/2 / 2011' , ' 12/2 / 2011' , '13/2 / 2011' ],

'Product' : [ 'Umbrella' , ' Matress' , 'Badminton' , ' Shuttle' ],

'Last_Price' : [ 1200 , 1500 , 1600 , 352 ],

'Updated_Price' : [ 1250 , 1450 , 1550 , 400 ],

'Discount' : [ 10 , 10 , 10 , 10 ]})

  
# Create indexes

df.index = [ 'Item 1' < / code> , 'Item 2' , ' Item 3' , 'Item 4' ]

 
# Print the data frame

print (df)

Output:

Now we want to find out the index marks of all elements with "Update_Price" greater than 1000.

# Select all lines that meet the criteria
# convert the collection of index labels to a list.

Index_label = df.query ( 'Updated_Price & gt; 1000' ). Index.tolist ()

 
# Print all labels

print (Index_label)

Output:





Tutorials