简体   繁体   中英

Get Dataframe index based off of list of columns and values

I am trying to return the indexes that the Name Column is 'Mike', State Column is 'Operational' / 'Broken', the Likelihood Column is 'High' and Status Column is 'Open' / 'Closed. The index should be 1 and 2 for this example.

import pandas as pd
df = pd.DataFrame(columns=['Name', 'State', 'Likelihood', 'Status']
df['Name'] = ['John', 'Mike', 'Mike', 'Jeff']
df['State'] = ['Operational', 'Operational', 'Broken', 'Operational' ]
df['Likelihood'] = ['High', 'High', 'Low', 'High']
df['Status'] = ['Open', 'Closed', 'Open', 'Closed']

print(df.index[df[['Name', 'State', 'Likelihood', 'Status']].isin(['Mike','Operational','Broken', 'High', 'Low' 'Open', ]).all(axis=1)])

Currently no luck on it printing index 1 and 2...Currently only printing 2

You can do it this way

print(df[df.Name.isin(['Mike'])& (df.State.isin(['Operational','Broken'])| df.Likelihood.isin(['High','Low'])| df.Status.isin(['Open']))])

Output

Name        State Likelihood  Status
Mike  Operational       High  Closed
Mike       Broken        Low    Open

One way to do multiple boolean masks in dataframe in a clean way is:

df[
   df['Name'].eq('Mike') &
   df['State'].isin(['Operational', 'Broken']) &
   df['Likelihood'].isin(['High', 'Low']) &
   df['Status'].isin(['Open', 'Closed'])
]

Output:

    Name    State        Likelihood     Status
1   Mike    Operational     High        Closed
2   Mike    Broken          Low          Open

If you want indices:

df[
   df['Name'].eq('Mike') &
   df['State'].isin(['Operational', 'Broken']) &
   df['Likelihood'].isin(['High', 'Low']) &
   df['Status'].isin(['Open', 'Closed'])
].index.tolist()

Output:

[1, 2]

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