Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

python - 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...