首页 > 解决方案 > 如何将浮点格式的熊猫数据框更改为小数点后 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 给出“格式不完整”错误。

标签: pythonpandascsvformat

解决方案


使用旧样式格式:

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%

推荐阅读