Abhinav
Abhinav

Reputation: 195

Add data above index pandas and write to excel sheet

So the dataframe I have is like this,

                     
Status                  Count      
Success                   2
Error                     2

I set the index to status column, but thats not all what i need. I need to display something like this, with some text above index name.

Complete Data Backup  
Status                 Count     
Success                   2
Error                     2

So far, Ive tried this code which displayed the format I want, but it doesnt appear in excel when I write to excel using df1.to_excel()

df1 = df1.set_index('Status').rename_axis('Complete Data Backup', axis=1)

What am I missing?

Upvotes: 2

Views: 494

Answers (1)

Laurent
Laurent

Reputation: 13518

With the following dataframe:

import pandas as pd

df = pd.DataFrame({"Status": ["Success", "Error"], "Count": [2, 2]})

print(df)
# Output
    Status  Count
0  Success      2
1    Error      2

Here is one way to do it using advanced indexing:

df.columns = pd.MultiIndex.from_product(
    [("Complete Data Backup",), ("Status", "Count")]
)

print(df)
# Output
  Complete Data Backup      
                Status Count
0              Success     2
1                Error     2

And then:

df.to_excel("file.xlsx")

In file.xlsx:

enter image description here

Upvotes: 1

Related Questions