I have a dataframe like
A B
1 2
5 5
0 5
And i want the output datafrme be like
A B C
1 2 50.00%
5 5 100.00%
0 5 0.00%
i have tried using standard method
df['C']=((df['A'] / df['B']) *100.00).round(2).astype(float)
But when i export the dataframe to excel it gets conveted to single decimals. Can you please help? i have tried to use astype(str) to get decimals correctly for some numbers but then i cannot perform excel formulation on that column.
I figured out a way using the code below
from io import BytesIO
with BytesIO() as b:
# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(b, engine='xlsxwriter')
data_df_final.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format2 = workbook.add_format({'num_format': '0.00%'})
worksheet.set_column('AD:AD', None, format2)
writer.save()
return HttpResponse(b.getvalue(), content_type='application/vnd.ms-excel')
However the problem is the column position can be dynamic in excel so AD position can change as per column name in excel . can anyone suggest a solution.