我有 2 个数据框要合并:
first_df=pd.DataFrame([['2001','Abu Dhabi','100-','462'],['2001','Abu Dhabi','100','44'],['2001','Abu Dhabi','200','462'],['2001','Dubai','100-','40'],['2001','Dubai','100','30'],['2001','Dubai','200','51'],['2002','Abu Dhabi','100-','300'],['2002','Abu Dhabi','100','220'],['2002','Abu Dhabi','200','56'],['2002','Dubai','100-','55'],['2002','Dubai','100','67'],['2002','Dubai','200','89']],columns=['Year','Emirate','Capacity','Number']) second_df=pd.DataFrame([['2001','Abu Dhabi','Performed','45'],['2001','Abu Dhabi','Not Performed','76'],['2001','Dubai','Performed','90'],['2001','Dubai','Not Performed','50'],['2002','Abu Dhabi','Performed','78'],['2002','Abu Dhabi','Not Performed','45'],['2002','Dubai','Performed','76'],['2002','Dubai','Not Performed','58']],columns=['Year','Emirate','Type','Value'])
所以我为两个数据帧设置了 multiIndex:
first=first_df.set_index(['Year','Emirate']) second=second_df.set_index(['Year','Emirate'])
并合并:
merged=first.merge(second,how='outer',right_index=True,left_index=True)
结果如下:
| Year , Emirate | Capacity | count | friday | count |
|:----------------------|:-----------|--------:|:--------------|--------:|
| ('2001', 'Abu Dhabi') | 100- | 462 | Performed | 45 |
| ('2001', 'Abu Dhabi') | 100- | 462 | Not Performed | 76 |
| ('2001', 'Abu Dhabi') | 100 | 44 | Performed | 45 |
| ('2001', 'Abu Dhabi') | 100 | 44 | Not Performed | 76 |
| ('2001', 'Abu Dhabi') | 200 | 657 | Performed | 45 |
所以连接在一起的两个数据帧不应该有重复(比如第一次合并)或向下移动(比如 concat 变体)。什么可以是使 2 个数据帧很好地对齐的解决方案?
qq_遁去的一_1
慕婉清6462132
相关分类