如何以浮点格式将 pandas 数据框保存为带小数点后两位的百分比 [英] How to save pandas dataframe with float format changed to percentage with 2 decimal places
问题描述
根据文档( https://pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame.to_csv.html ),我们可以在dataframe的to_csv方法中指定浮点数格式.
According to the documentation (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html), we can specify the floating number format in to_csv method of dataframe.
我尝试使用float_format=':,.2%'
参数将浮点格式更改为2个十进制百分比,该参数可在python控制台(如'{:,.2%}'.format(3.14)
)上使用,但to_csv会给出格式不完整"错误.
I try to change the float format to 2 decimal percentage with float_format=':,.2%'
parameter, which works on python console (like '{:,.2%}'.format(3.14)
), but to_csv gives "incomplete format" error.
推荐答案
使用旧样式格式:
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:
You could multiply your data by 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%
这篇关于如何以浮点格式将 pandas 数据框保存为带小数点后两位的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!