Write DataFrame to excel along with the axis name

I'm trying to write a dataframe along with the axis name to an excel file.

df = pd.DataFrame({'350p HP': [7844, 2, 1],
                'tc206':[1721.5, 0.44, 1.81],
                'tcs208':[77.52, 0.02, 0.11], 
                'sas22':[1330.8, 0.34, 0.58],
                'tss21':[3070.2, 0.78, 0.56],
                'tas22': [5619.2, 1.43, 1.03]}, index=['DP', 'DP/REP', 'AF'])
df.rename_axis('col name', axis=1, inplace=True)

here is the dataframe I'm trying to write with the axis name col name. I tried with both engine='openpyxl' and engine='xlsxwriter'.

`excel_file = "test.xlsx"
 writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
 df.to_excel(writer, sheet_name='axisname')
 writer.save()`

I prefer to make it work with xlsxwriter as there are other dependencies. I'm trying to find a solution for this. Please let me know if there is a way to do this.

Upvotes: 2

Views: 930

Answers (2)

Corralien
Corralien

Reputation: 120429

Use index_label:

From the documentation:

index_label
Column label for index column(s) if desired. If not specified, and header and index are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.

df.to_excel('test.xlsx', index_label='col name')

Upvotes: 2

jezrael
jezrael

Reputation: 862751

You can pass df.columns.name to parameter index_label:

 df.to_excel(writer, index_label=df.columns.name)

Upvotes: 2

Related Questions