Home > other >  Pick row(s) in data frame with many columns
Pick row(s) in data frame with many columns

Time:09-16

My goal is to pick row index(s), given row data.

For instance, if a row data, list ['Parrot', 'Captive','BIG',0,0] is given,the answer should be 2 for my data frame below because the row data is located at index 2 row.

The problem is the number of columns are too many.

In this simple case, the number of columns is 5 (X1 ~ X5), though.

Is there a efficient way?

import pandas as pd
df = pd.DataFrame({'X1': ['Falcon', 'Falcon', 'Parrot', 'Parrot'],
                   'X2': ['Captive', 'Wild', 'Captive', 'Wild'],
                   'X3': ['BIG', 'SMALL', 'BIG', 'SMALL'],
                   'X4': [0,1,0,0],
                   'X5': [1,0,0,0]})
df

CodePudding user response:

You can use the all function to make sure the row has all True boolean.

df[df.isin(['Parrot', 'Captive','BIG',0,0]).all(axis=1)].index

Int64Index([2], dtype='int64')

CodePudding user response:

df[(df.X1 == 'Parrot') & (df.X3 == 'BIG')].index[0]

will give you the 2 you are looking for

  • Related