python - 如何将浮点格式的熊猫数据框更改为小数点后 2 位的百分比
问题描述
根据文档(https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html),我们可以在数据帧的 to_csv 方法中指定浮点数格式。
我尝试使用参数将浮点格式更改为 2 个小数百分比float_format=':,.2%'
,该参数适用于 python 控制台(如'{:,.2%}'.format(3.14)
),但 to_csv 给出“格式不完整”错误。
解决方案
使用旧样式格式:
df = pd.DataFrame(np.random.random((5,5)))
df.to_csv('test.out', float_format='%.2f', index=False, header=False)
!type test.out
输出:
0.10,0.90,0.65,0.78,0.70
0.03,0.45,0.75,0.92,0.94
0.49,0.64,0.47,0.28,0.50
0.48,0.09,0.86,0.33,0.55
0.37,0.85,0.97,0.19,0.68
您可以将数据乘以 100:
df = pd.DataFrame(np.random.random((5,5)))*100
df.to_csv('test.out', float_format='%.0f%%', index=False, header=False)
!type test.out
输出:
48%,73%,30%,4%,54%
76%,53%,58%,41%,22%
97%,44%,58%,59%,60%
95%,85%,47%,67%,88%
4%,73%,66%,70%,97%
推荐阅读
- laravel - 如何从下拉列表中获取值并将该值自动传递给另一个表单?
- github - 比较 GitHub 网站上特定分支的两次提交
- python - ldap3:获取用户的电子邮件地址
- c# - 在为 C# Web 应用程序配置 IIS 身份验证方面需要帮助,以确保它模拟用户 NT 登录访问
- python - 值是预期值,但 if 语句无法识别?
- tensorflow - 尝试从 TensorFlow Hub 导入 Elmo 模块时出错?
- docker - 来自守护进程的错误响应:获取 https://registry-1.docker.io/v2/:net/http: 请求在等待连接时取消(Client.Timeout exceeded
- c++ - 构建成功但不会给出正确的输出
- wordpress - 无法为我的 AWS Bitnami wordpress 网站创建证书
- javascript - Bootstrap 4:如何在第一次触发后删除 modal 的 show.bs.modal 事件