I want to combine the following DataFrames:
DF1:
value1 value2
index
0 a0 b0
1 a1 b1
2 a2 b2
3 a3 b3
DF2:
value1 value2
index
0 c0 d0
1 c1 d1
2 c2 d2
3 c3 d3
DF3:
value1 value2
index
0 e0 f0
1 e1 f1
2 e2 f2
3 e3 f3
I would like to combine them into a single DataFrame where we take one column from each DataFrame at a time. The columns should be named by the same column names in the first level and with a list of given names for the second level where this list has the same size as the number of DataFrames (in the example it is 3). The expected DataFrame would look like this for a list of names [M1, M2, DIF]:
value1 value2
M1 M2 DIF M1 M2 DIF
index
0 a0 c0 e0 b0 d0 f0
1 a1 c1 e1 b1 d1 f1
2 a2 c2 e2 b2 d2 f2
3 a3 c3 e3 b3 d3 f3
What is the easiest/fastest way to do this?
Let us do concat
df=pd.concat([df1,df1,df1],keys=list('ABC'),axis=1).swaplevel(0,1,axis=1).sort_index(level=0,axis=1)
value1 value2
A B C A B C
index
0 a0 a0 a0 b0 b0 b0
1 a1 a1 a1 b1 b1 b1
2 a2 a2 a2 b2 b2 b2
3 a3 a3 a3 b3 b3 b3
Update
l=['M1', 'M2', 'DIF']
pd.concat([df1,df1,df1],keys=['M1', 'M2', 'DIF'],axis=1).swaplevel(0,1,axis=1).reindex(columns=pd.MultiIndex.from_product([list(df1),l]))
value1 value2
M1 M2 DIF M1 M2 DIF
index
0 a0 a0 a0 b0 b0 b0
1 a1 a1 a1 b1 b1 b1
2 a2 a2 a2 b2 b2 b2
3 a3 a3 a3 b3 b3 b3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.