develarist
develarist

Reputation: 1375

How to index a pandas DataFrame element in last column based on criteria being met in two other columns?

A pandas dataframe has 4 columns:

df.columns = ['col1', 'col2', 'question', 'answer']

How do I index a single entry of the 'answer' column, by indexing the dataframe based on criteria being met for the first columns?

i.e.:

df['col1'=='apple' and 'col2'=='guitar'].answer

Upvotes: 0

Views: 17

Answers (1)

jezrael
jezrael

Reputation: 863166

You can select values after filtering, but not recommended, because if set values similar way possible warning:

s = df.loc[(df['col1']=='apple') & (df['col2']=='guitar')].answer

Better way is use DataFrame.loc for filter by mask and by column name:

s = df.loc[(df['col1']=='apple') & (df['col2']=='guitar'), 'answer']

Or using DataFrame.query:

s = df.query("col1=='apple' and col2=='guitar'").answer

Output is one or more values in Series, if need first one to scalar:

first = s.iat[0]

If need solution working also if no match:

first  = next(iter(s), 'no match')

Upvotes: 1

Related Questions