jjaredrides
jjaredrides

Reputation: 3

How to move columns of a dataframe to be multi-index headers?

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

I'd like to modify the code above to where the first 2 columns in the dataframe are multi-index columns? So moving "Col1" and "Col1_1" to be columns in a muli-index dataframe.

Upvotes: 0

Views: 887

Answers (1)

Subasri sridhar
Subasri sridhar

Reputation: 831

See if this is what you are asking for :

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

Upvotes: 2

Related Questions