Zanam
Zanam

Reputation: 4807

Print dataframe to excel with name

I have a dataframe df which has values as:

Year    c1      c2      c3      c4
2013    9.51    7.74    10.41   
2014    21.53   8.44    25.92   14.24
2015    13.85   8.09    16.10   1.92
2016    10.51   8.28    11.49   0.82
2017    7.92    10.70   7.33    
2018    28.53   20.13   31.06   4.38
Average 15.31   10.56   17.05   5.34

df.columns

Index(['c1', 'c2', 'c3', 'c4'], dtype='object', name='PeakPeriod')

df.to_excel prints only the table not the column name PeakPeriod

Is there a way to print this to excel so that it looks as the following:

enter image description here

Upvotes: 1

Views: 194

Answers (1)

Andrea Mannari
Andrea Mannari

Reputation: 1012

You can use this code:

writer = pd.ExcelWriter("file_name.xlsx")
df.to_excel(writer, 'Sheet1',startrow = 1)  
workbook1 = writer.book
worksheets = writer.sheets
worksheet1 = worksheets['Sheet1']
worksheet1.write(0, 0, df.columns.name)  
writer.save()
writer.close()

Upvotes: 1

Related Questions