0

Is it possible to change a single level column dataframe to a multi-column dataframe? If we have a dataframe like this,

import pandas as pd
    
df = pd.DataFrame({
    'a': [0, 1, 2, 3],
    'b': [4, 5, 6, 7],
    'c': [3, 5, 6, 2],
    'd': [1, 5, 7, 0],
})

can we change it's column names as below?. So, briefly what I am trying to do is to have 2-levels of column index without changing the values of the dataframe.

    A       B
    a   b   c   d
0   0   4   3   1
1   1   5   5   5
2   2   6   6   7
3   3   7   2   0

Any help?

2
  • Your input code doesn't generate the expected dataframe. Commented Feb 3, 2021 at 18:26
  • @Scott BostonThank you for the notification, I have corrected it Commented Feb 3, 2021 at 21:40

1 Answer 1

1

IIUC, use pd.MultiIndex.from_tuples to create multiindex header and assign to the dataframe.columns:

df = pd.DataFrame({
    'a': [0, 1, 2, 3],
    'b': [4, 5, 6, 7],
    'a2': [3, 5, 6, 2],
    'b2': [1, 5, 7, 0],
})

df.columns=pd.MultiIndex.from_tuples([('A','a'),('A','b'),('B','c'),('B','d')])
df

Output:

   A     B   
   a  b  c  d
0  0  4  3  1
1  1  5  5  5
2  2  6  6  7
3  3  7  2  0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.