You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于另一个DataFrame筛选数据?求更优实现方案

Better Ways to Filter DataFrame Rows by Matching IDs from Another 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 one dummy 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 source df has no duplicate rows for the same Id and Food combination

Either of the two methods above will get you the exact result you want with less code and better readability.

内容的提问来源于stack exchange,提问作者Nabih Bawazir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:43