Python Team
Python Team

Reputation: 1171

Add new header to existing columns in excel using pandas

I have a dataframe like below mentioned . I want to add new header in existing dataframe as expected result . Can anyone please help me to do this.

One:

   Name    Std   Tamil  Maths   Score  Result     Status
  Shankar   10    90     100     190     Pass      Good
  Shankar   10    50      20      70     Fail      Bad

I want to add Subjects and Grade as a header in existing frame

Expected Result:

                 Subjects         Grade
  Name    std   Tamil  Maths    Score  Result       Status
 Shankar   10    90     100      190     Pass        Good
 Shankar    10    50      20       70     Fail        Bad

enter image description here

Kindly anyone help me to do the expected result

Recently got like below: when i use like [['']*1+['']*1+['Subjects'] * 2 + ['Grade'] * 2 + ['']*1, dfnew.columns] enter image description here

I want to remove empty row and first column which is created automatically.

Upvotes: 1

Views: 1118

Answers (1)

jezrael
jezrael

Reputation: 862921

Create MultiIndex by set_index with all columns which cannot be set to MultiIndex in columns and then assigh nested lists:

df = df.set_index(['Name','Std'])
df.columns = [['Subjects'] * 2 + ['Grade'] * 2, df.columns]
print (df)
            Subjects       Grade       
               Tamil Maths Score Result
Name    Std                            
Shankar 10        90   100   190   Pass
Kumar   10        50    20    70   Fail

Upvotes: 1

Related Questions