Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of index while outputting multi header pandas dataframe to excel

I have a pandas dataframe as below:

header = [np.array(['location','location','location','location2','location2','location2']), 
np.array(['S1','S2','S3','S4','S5','S6'])] 
df = pd.DataFrame(np.random.randn(5, 6), columns = header ) 
df

I want to export my dataframe to an excel sheet ignoring the index. Here is my code which exports my dataframe to excel spreadsheet but with index. when I am using the parameter, index = False, It gives me an error.

# output all the consolidated input to an excel sheet
out_file_name = os.path.join(folder_location, "templates", future_template)
writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df.to_excel(writer, sheet_name='Ratings Inputs')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
like image 459
Shanoo Avatar asked Sep 05 '25 03:09

Shanoo


1 Answers

Better late than never for those looking for an easier workaround, keeping in mind it does not reset the columns to start at A. Use:

writer.sheets['Ratings Inputs'].set_column(0, 0, None, None, {'hidden': True})

Full code:

import numpy as np
import pandas as pd
import xlsxwriter
import os

header = [np.array(['location','location','location','location2','location2','location2']), 
np.array(['S1','S2','S3','S4','S5','S6'])] 
df = pd.DataFrame(np.random.randn(5, 6), columns = header ) 

writer = pd.ExcelWriter('testdf.xlsx', engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df.to_excel(writer, sheet_name='Ratings Inputs')
#Removing index column 
writer.sheets['Ratings Inputs'].set_column(0, 0, None, None, {'hidden': True})
# Close the Pandas Excel writer and output the Excel file.
writer.close() 

Before:
Resulting excel with index column


After:
Resulting excel with index column removed

like image 71
Dana Yang Avatar answered Sep 07 '25 23:09

Dana Yang