简体   繁体   中英

How to move pandas data frame multiindex column into 2 rows

I have an issue with my data frame. I have a pandas data frame with MultiIndex Columns, so it means that in my data frame header I have tuples like ("A", 123"), ("B", 456"), ("C", 789). And I would like to create from this tuple 2 rows in the way that data frame will look like:

"A" "B" "C"
123 456 789
row row row
row row row
row row row

There are two possibilities for me. I can have a header in 2 rows, or I can have just one header but in 1 row after header, I will have my 2nd tuple element.

Can you help me with that? I tried dropping level but it didn't work.

If need convert MultiIndex to first 2 rows use MultiIndex.to_frame with transpose and DataFrame.append , last set default columns names:

mux = pd.MultiIndex.from_tuples([("A", 123), ("B", 456), ("C", 789)])
df = pd.DataFrame(0, columns=mux, index=[0])
print (df)
    A   B   C
  123 456 789
0   0   0   0

df1 = df.columns.to_frame().T.append(df, ignore_index=True)
df1.columns = range(len(df1.columns))
print (df1)
     0    1    2
0    A    B    C
1  123  456  789
2    0    0    0

If need move only second level select it by DataFrame.iloc and last remove second level by DataFrame.droplevel :

df2 = df.columns.to_frame().T.iloc[[1]].append(df, ignore_index=True).droplevel(1, axis=1)
print (df2)
     A    B    C
0  123  456  789
1    0    0    0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM