python-3.x - 计算熊猫的百分比
问题描述
我有一个像
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 中的列名进行更改。任何人都可以提出解决方案。
解决方案
推荐阅读
- ios - iOS 应用程序和地理编码的 Google Maps API 密钥限制
- typescript - Angular 中的模型
- html - 使用 css 选择器 jsoup 解析 html
- php - 如何使用 php 从 .ini 文件中删除部分
- typescript - 在 Yarn 工作区中使用 Typescript 引用时如何添加自定义类型定义?
- python - 如何增加散景中组标签之间的空间
- string - 查找第一个不同的字符串
- json - 有没有一种简单的方法来反序列化 JSON 字符串,将所有数组都保留为字符串?
- php - Inserting slash into CSS
- swift - Get nil when looking for file in subdirectory of main bundle