如何在Python中基于另一个DataFrame过滤目标DataFrame的指定行?
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

