首页 > 解决方案 > 计算熊猫的百分比

问题描述

我有一个像

A  B
1  2
5  5
0  5

我希望输出数据帧像

A  B  C
1  2  50.00%
5  5  100.00%
0  5  0.00% 

我试过使用标准方法

 df['C']=((df['A'] / df['B']) *100.00).round(2).astype(float)

但是,当我将数据框导出到 excel 时,它会转换为小数点。你能帮忙吗?我曾尝试使用 astype(str) 为某些数字正确获取小数,但随后我无法在该列上执行 excel 公式。


我想出了一种使用下面代码的方法

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')

但是问题是 excel 中的列位置可以是动态的,因此 AD 位置可以根据 excel 中的列名进行更改。任何人都可以提出解决方案。

标签: python-3.xpandas

解决方案


推荐阅读