首页 > 解决方案 > 比较不同数据框中的 2 列

问题描述

如果我有 2 个表 b ,c 并且我想去 c 并检查名为 parent 的列,如果值等于表 b 中列 PrentSKU 的值,则从表 b 中取出列 ChildSKU 的值并将其放入列 Style在表 c 中,否则什么也不做

我尝试使用比较方法,但表大小不同,所以它给了我一个错误,我也尝试了 for 循环,但它也给了我一个错误,即 Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我试过的代码:

 for row in c['ParentSKU']:
        if row == b['Parent']:
           b['Style'] == c['ChildSKU']
        else: break  

标签: pythonpandas

解决方案


你可以尝试这样的事情:

b = pd.DataFrame({'Parent':['a','b','c','d','e'],'ChildSKU':range(5)})

    Parent  ChildSKU
0   a   0
1   b   1
2   c   2
3   d   3
4   e   4

c = pd.DataFrame({'ParentSKU':['a','c','e']})

    ParentSKU   
0   a   
1   c   
2   e   

c['Style'] = c.merge(b,left_on='ParentSKU',right_on='Parent')['ChildSKU']

    ParentSKU   Style
0   a   0
1   c   2
2   e   4

推荐阅读