在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结合在一起:
df1中period
的值和df2中Period
索引的值
df1中的列标签Inbound
或Outbound
和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