将数据帧列与条件进行比较

2024-04-25 01:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧如下:

df1型:

ID   col1   col2    
1     A1     B1    
2     A2     B2     
3     A3     B3   
4     A4     B4   
5     A5     B5    
6     A6     B6    

df2型:

col1   col2   
 A1     B1     
 A2     O5   
 H3     B3     
 A4     B4    
 A5     66     
 A6     C6     

预期结果:我想根据条件生成一个结果df-df1的col1,col2中的每个值都应该存在于df2的col1,col2值中

预期结果df:

ID   col1   col2     Error
1     A1     B1      No mismatch with df2
2     A2     B2      col2 mismatch with df2
3     A3     B3      col1 mismatch with df2
4     A4     B4      No mismatch with df2
5     A5     B5      col2 mismatch with df2
6     A6     B6      col2 mismatch with df2

Tags: ida2a1withb1col2col1a4
2条回答

像这样的东西应该可以达到目的,但可能有一个更简单的方法。你知道吗

diff = pd.concat([df1[col] == df2[col] for col in df1], axis=1)

def m(row):
    mismatches = []
    for col in diff.columns:
        if not row[col]:
            mismatches.append(col)
    if mismatches == []:
        return 'No mismatch'
    return 'Mismatches: ' + ', '.join(mismatches)

df1['Error'] = diff.apply(m, axis=1)

创建具有字典理解和与^{}比较的帮助程序数据帧:

m = pd.DataFrame({c: ~df1[c].isin(df2[c]) for c in ['col1','col2']})
print (m)
    col1   col2
0  False  False
1  False   True
2   True  False
3  False  False
4  False   True
5  False   True

然后^{}用掩码^{}测试每行至少一个True,用矩阵乘法^{}获取列名:

df1['Error'] = np.where(m.any(axis=1), 
                        m.dot(m.columns + ', ').str.rstrip(', ') + ' mismatch with df2', 
                       'No mismatch with df2')
print (df1)
   ID col1 col2                   Error
0   1   A1   B1    No mismatch with df2
1   2   A2   B2  col2 mismatch with df2
2   3   A3   B3  col1 mismatch with df2
3   4   A4   B4    No mismatch with df2
4   5   A5   B5  col2 mismatch with df2
5   6   A6   B6  col2 mismatch with df2

相关问题 更多 >