I am writing multiple sheets in to excel file using pandas:
df_res = {'name' : df_1,
'name_2': df_2}
sheet_names = ['first','second']
with pd.ExcelWriter('my_file.xlsx') as writer:
for new_name, (name,df) in zip(sheet_names, df_res.items()):
df.to_excel(writer, sheet_name = new_name)
My structure of multiple dfs is that they are in a dictionary. In each of those two dfs there are certain columns which format I would like to change to a percentage - same as selecting a column in excel and click on % sign to convert it to percentage type.
I achieve the formatting by adding the following to my for loop:
workbook = writer.book
worksheet = writer.sheets[new_name]
format_percentages = workbook.add_format({'num_format': '0%'})
# below I change a single column type
worksheet.set_column('J:J', 18, format_percentages)
The problem is that my wanted columns do not appear in the same order. if below were my dfs:
# df_1
A B C # immitating excel column names
name sales difference
A 10 50
# df_2
A B C # immitating excel column names
name difference sales
B 10 50
I could not call the format on column B or C since difference which I would like to be represented as percentage type appears in different columns.
Is there a way to change column type by giving its column name?