场景:想筛选df1中“列1+列2”组合在df2中的组合

    1. import pandas as pd
    2. # 先创建两个dataframe
    3. df1 = pd.DataFrame([['A1', 'B1'], ['A1', 'B2'], ['A2', 'B1'], ['A2', 'B2']], columns=['列1', '列2'])
    4. df2 = pd.DataFrame([['A1', 'B1'], ['A2', 'B2']], columns=['列1', '列2'])
    5. # 错误写法
    6. error_df = df1[df1['列1'].isin(df2['列1']) & df1['列2'].isin(df2['列2'])]
    7. # 正确写法
    8. right_df = df1[(df1['列1']+df1['列2']).isin(df2['列1']+df2['列2'])]
    9. print('【df1】\n', df1)
    10. print('【df2】\n', df2)
    11. print('【错误结果】\n', error_df)
    12. print('【正确结果】\n', right_df)

    image.png