python合并带有列和索引的两个数据框

时间:2019-11-19 03:36:42

标签: python dataframe merge

在Python 3.7中工作

有没有一种方法可以使用列和索引来连接两个数据框?

例如

>>> df1
             period  Inbound  Outbound
0           peak AM        3         0
1  off-peak weekday       11        11
2    Contra-peak PM        4         4
3  off-peak weekend       16        16
4           peak PM        0         4
5    Contra-peak AM        4         3

>>> df2 # after groupby
                            Year  Weekday TAG  
Period           Direction                     
off-peak weekend Inbound      10           10  
                 Outbound     10           10  
peak AM          Inbound      10           10  
peak PM          Outbound     10           10

>>> df2.index

MultiIndex(levels=[['off-peak weekend', 'peak AM', 'peak PM'], ['Inbound', 'Outbound']],
           codes=[[0, 0, 1, 2], [0, 1, 0, 1]],
           names=['Period', 'Direction'])

我想通过以下方式将df1与df2结合在一起:

  1. df1中period的值和df2中Period索引的值

  2. df1中的列标签InboundOutbound和df2中的Direction索引值

我能想到的唯一解决方案是循环遍历df2,以将值分配到df1中的正确位置。有更好的方法吗?

我要寻找的结果数据框是这个。

             period  Inbound  Outbound  new_col_inbound  new_col_outbound
0           peak AM        3         0               10                 0
1  off-peak weekday       11        11                0                 0
2    Contra-peak PM        4         4                0                 0
3  off-peak weekend       16        16               10                10
4           peak PM        0         4                0                10
5    Contra-peak AM        4         3                0                 0

0 个答案:

没有答案