熊猫合并并为重复的列创建一个多索引

时间:2018-08-29 06:04:36

标签: python pandas

我有两个数据框

sessions = DataFrame({"ID":[1,2,3,4,5],"2018-06-30":[23,34,45,67,75],"2018-07-31":[32,43,45,76,57]})
leads = DataFrame({"ID":[1,2,3,4,5],"2018-06-30":[7,10,28,15,30],"2018-07-31":[7,10,28,15,30]})

我想合并ID上的两个数据框,然后创建一个如下所示的多索引:

enter image description here

我该怎么办?

直接创建pandas.merge会创建我不想要的后缀_x,_y。

1 个答案:

答案 0 :(得分:3)

在两个DataFrame中将ID中的concatMultiIndex一起使用,然后将set_index中的swaplevelsort_index用于列中的预期df = (pd.concat([sessions.set_index('ID'), leads.set_index('ID')], axis=1, keys=['sessions','leads']) .swaplevel(0,1,axis=1) .sort_index(axis=1, ascending=[True, False]) ) print (df) 2018-06-30 2018-07-31 sessions leads sessions leads ID 1 23 7 32 7 2 34 10 43 10 3 45 28 45 28 4 67 15 76 15 5 75 30 57 30

@"(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:1|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:[\D]*)(?<time>\d{1,2}\:\d{2}\s(?:A|P)M)";