如何将DataFrame列值映射至另一DataFrame双列并提取匹配行
Solution to Filter Rows Where Both G1 and G2 Match df1's NAME Column
Got it, I see where the issue was—your original code uses the logical OR (|) operator, which keeps any row where either G1 or G2 is in df1's NAME list. What you need is the logical AND (&) operator, which will only keep rows where both G1 and G2 are present in df1['NAME'].
Step-by-Step Fix:
Replace the
|with&in your boolean indexing to enforce both columns match the NAME values:# Corrected filtering code filtered_df = df2[(df2['G1'].isin(df1['NAME'])) & (df2['G2'].isin(df1['NAME']))]This works because:
df2['G1'].isin(df1['NAME'])checks if the G1 value exists in df1's NAME columndf2['G2'].isin(df1['NAME'])does the same for G2- The
&operator ensures both conditions are true for a row to be kept
Expected Output:
Running the corrected code will give you exactly the rows you're looking for:
G1 G2 Value 0 AB2 AB3 5 1 AB3 AB2 5 2 AB2 AB2 4 5 AB5 AB6 4 10 AB776 AB776 1 11 AB845 AB776 8
内容的提问来源于stack exchange,提问作者user2110417
相关产品推荐
相关产品推荐

