1

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.

1 Answer 1

2

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
1
  • Thank you very much for your help. You provided a very nice and clever way to do that. Thank you! Feb 18, 2021 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.