直面数据帧之间的价值观



我正试图找到一种方法来对抗包含在具有不同列名的不同数据帧中的值的相等性。

label = {
'aoo' : ['a', 'b', 'c'],
'boo' : ['a', 'b', 'c'],
'coo' : ['a', 'b', 'c']
'label': ['label', 'label', 'label']
}
unlabel = {
'unlabel1' : ['a', 'b', 'c'],
'unlabel2' : ['a', 'b', 'c'],
'unlabel3': ['a', 'b', 'hhh']
}
label = pd.DataFrame(label)
unlabel = pd.DataFrame(unlabel)

所需输出是一个数据帧,其中包含值相等的列和列标签。如果单个值不等于unlabel['unlabel3'],我不想在输出中保留这些值。

desired_output = {
'unlabel1' : ['a', 'b', 'c'],
'unlabel2' : ['a', 'b', 'c'],
'label' : ['label', 'label', 'label']
}

如果标签上有数字,我可以尝试np.where,但我找不到类似的字符串助手。

你能帮忙吗?感谢

您可以使用pd.merge并指定要与left_onright_on合并的列

out = unlabel.merge(label, left_on=['unlabel1', 'unlabel2', 'unlabel3'], right_on=['aoo', 'boo', 'coo'], how='left').drop(['unlabel3', 'aoo', 'boo', 'coo'], axis=1)
print(out)
unlabel1 unlabel2  label
0        a        a  label
1        b        b  label
2        c        c    NaN

最新更新