如何基于另一个DataFrame筛选数据?求更优实现方案
Hey there! Your current code works perfectly fine, but we can simplify it to be more concise and efficient. Here are two better approaches:
1. Use isin() for Direct Filtering
This is the most straightforward method—we directly check which rows in df have an Id present in df2['Id']:
result_df = df[df['Id'].isin(df2['Id'])]
This avoids creating extra columns, merging, or deduplicating (since your original df has no duplicate rows for the same Id+Food pair). It’s clean and easy to read.
2. Use Inner Join with merge()
Instead of a left join followed by filtering, an inner join will only keep rows where the Id exists in both DataFrames. This cuts out the extra steps of adding a dummy column and filtering:
result_df = df.merge(df2, on='Id', how='inner')
Since df2 only contains the Id column, the merged result will automatically have just the Id and Food columns you need—no need to reselect columns afterward.
Why These Are Better Than Your Original Approach
Your original code works, but it includes unnecessary steps:
- Adding the
onedummy column isn’t required - Using a left join + filter is redundant when an inner join does the job directly
- The
drop_duplicates()call is unnecessary here, as your sourcedfhas no duplicate rows for the sameIdandFoodcombination
Either of the two methods above will get you the exact result you want with less code and better readability.
内容的提问来源于stack exchange,提问作者Nabih Bawazir

