如何将数据框的列移动为多索引标头?

问题描述

data = {'0':['Col1','Col1_1',10,9,8],'1':['Col1','Col1_2','2':['Col2',8]}
df1 = pd.DataFrame(data)

我想将上面的代码修改为数据框的前2列是多索引列?因此,将“ Col1”和“ Col1_1”移动为多索引数据框中的列。

解决方法

看看这是否是您要的:

df1.columns=pd.MultiIndex.from_arrays(df1.iloc[0:2].values)

#delete the first 2 rows because they are also the columns
df1=df1.iloc[2:]

df1.reset_index(drop=True)

enter image description here