2 回答
TA贡献1780条经验 获得超5个赞
pd.concat([df1, df2], axis=1).sort_index(axis=1)
编辑:
print (df1)
Column
col5 col2
0 1 3
1 2 4
print (df2)
Column
col1
0 5
1 6
df = pd.concat([df1, df2], axis=1)
c = df.columns.tolist()
df = df.reindex(c[:1] + sorted(c[1:]), axis=1)
print (df)
Column
col5 col1 col2
0 1 5 3
1 2 6 4
EDIT1:与一起使用DataFrame.xs
,DataFrame.sort_index
添加原始非选定的caolumns值Index.union
和最后更改顺序DataFrame.reindex
:
print (df)
Column a
col2 col1 col5 col1 col3
0 1 5 3 5 4
1 2 6 4 7 7
cols = (df.xs('Column', drop_level=False, axis=1, level=0)
.sort_index(ascending=False, axis=1).columns)
print (cols)
MultiIndex([('Column', 'col5'),
('Column', 'col2'),
('Column', 'col1')],
)
df = df.reindex(cols.union(df.columns, sort=False), axis=1)
print (df)
Column a
col5 col2 col1 col1 col3
0 3 1 5 5 4
1 4 2 6 7 7
添加回答
举报