0
$\begingroup$

I have two dataframes that share an ID number column. I'd like to filter df1's rows based on two conditions: 1) it shares the ID with df2 and 2) it meets a condition in a column in df2.

I have this code:

filter = df1[df1['ID'].isin(df2['ID']) & (df2['section_name'] == 'Writing 1')]

Could something like this work? Or am I going about this improperly? The first half of this code works: I can match the ID columns and get expected output. When I add the second condition, it returns zero results, but there are cells with 'Writing 1' in a column called 'section_name' in df2.

$\endgroup$

2 Answers 2

0
$\begingroup$

To answer your question:

  • What you are doing will work (probably) but why are you making this hard.
  • I will suggest you to merge your two dataframes based on the ID. And then it will be easier for you to write any conditions/filters that you want.

I hope I answered your question.

$\endgroup$
1
$\begingroup$

This should work:

filter = df1[df1['ID'].isin(df2[df2['section_name']=='Writing 1']['ID'])]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.