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

如何在Python中基于另一个DataFrame过滤目标DataFrame的指定行?

Filter and Remove Rows from a DataFrame Based on Another DataFrame in Python

Got it, let's break down how to solve this problem. You need to remove rows from df1 where the code value doesn't exist in the Event column of df2—in your example, that means keeping only the row with code 123 and dropping the other two. Here are a couple of simple, reliable ways to do this with pandas:

Method 1: Use isin() for Direct Filtering

This is the most straightforward approach. The isin() method checks if each value in df1['code'] is present in df2['Event'], then we use that boolean result to filter df1.

import pandas as pd

# First, recreate your sample DataFrames
df1 = pd.DataFrame({
    'system': ['AIII-01', 'CIII-04', 'LV-02'],
    'code': [423, 123, 142]
})

df2 = pd.DataFrame({
    'StatusMessage': ['Gearbox warm up'],
    'Event': [123]
})

# Filter df1 to keep only rows where code is in df2's Event column
filtered_df = df1[df1['code'].isin(df2['Event'])]

# Output the result
print(filtered_df)

Running this will give you the desired result:

system  code
1  CIII-04   123

Method 2: Drop Rows Directly from the Original DataFrame

If you want to modify df1 in-place instead of creating a new DataFrame, you can find the indices of the rows to remove and use drop():

# Get indices of rows where code is NOT in df2's Event column
indices_to_drop = df1[~df1['code'].isin(df2['Event'])].index

# Drop those rows (use inplace=True to modify df1 directly)
df1.drop(indices_to_drop, inplace=True)

print(df1)

The ~ operator here reverses the boolean condition—so we're targeting rows that don't match the values in df2['Event'].

Important Note

Make sure the data types of df1['code'] and df2['Event'] match! If one is an integer and the other is a string, isin() won't find matches. You can convert types with something like df2['Event'] = df2['Event'].astype(int) if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:07:43