简体   繁体   中英

How to identify index based off of specific values in specific columns?

I am trying to get a list of indexes that have a specific column and value

import pandas as pd
df = pd.DataFrame(columns=['A', 'B', 'C', 'D', 'E']
df['A'] = ['Cat', 'Dog', 'Bird']
df['B'] = ['Car', 'Truck', 'Car']
df['C'] = ['California', 'Nevada', 'Florida']
df['D'] = ['Coffee', 'Juice', 'Water']
df['E'] = ['Arm', 'Leg', 'Head']

How would I get the index for list of columns 'A', 'B', 'D' that contain the list of values 'Cat', 'Car', and 'Coffee'? In this example the index should be 0

If order of values is not important and not duplicates seelct columns by list and test by DataFrame.isin with DataFrame.all if match all values, last filter index values in boolean indexing :

i = df.index[df[['A', 'B', 'D']].isin(['Cat','Car','Coffee']).all(axis=1)]
print (i)
Int64Index([0], dtype='int64')

If order is important you can compare values by list in DataFrame.eq :

i = df.index[df[['A', 'B', 'D']].eq(['Cat', 'Car', 'Coffee']).all(axis=1)]
print (i)
Int64Index([0], dtype='int64')

If need scalar working also if no match then use:

out = next(iter(i), 'no match')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM