0

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.

R.singh
  • 259
  • 1
  • 13
  • Your problem is more **how to format while exporting a dataframe to excel**? if yes, have a look at [this](https://stackoverflow.com/questions/29974672/writing-pandas-dataframe-to-excel-with-different-formats-for-different-columns) – Ben.T Mar 20 '20 at 13:48
  • Hi @Ben.T i have edited the question could you please suggest a solution? – R.singh Mar 20 '20 at 18:15

0 Answers0