使用Python将计算结果格式化为保留两位小数的百分比

1 投票
3 回答
13457 浏览
提问于 2025-04-17 22:04

这些值是:

预算 = 11,000

实际 = 10,000

差异 = 预算 - 实际 (1,000)

total, would be the value of budget variable: 11,000

我的代码:

percent_val = variance/total
format_percent = {:.2f}.format(percent_val)
return format_percent

我以为上面的代码会返回值 9.09(保留两位小数)

return value: 9.09

这个视频展示了这个,但我不知道怎么用 {0:2.df} 这个字符串来实现?

http://www.youtube.com/watch?v=mmJPx6YsOMI

我怎么才能把 9.09 百分比格式化成数字,而不是字符串,这样我才能在后面进行计算?

3 个回答

1

如果你决定使用pandas和df,这里有一个快速的方法,如果你不介意把所有的pd数据设置为特定的精度。正如你所看到的,数据仍然可以保持它原来的精度使用。

import pandas as pd
import numpy as np

pd.set_option('precision',2)
df = pd.DataFrame(np.random.randn(5,2), columns = ['A','B'])
df
Out[15]: 
      A     B
0 -1.87  1.20
1 -0.55 -1.19
2  1.04  0.89
3 -0.65  0.30
4  0.07 -1.37

df.A[0] + 1.77777
Out[16]: -0.095449113301297794
3

你可以把显示格式放到pandas的显示选项里:

In [11]: df = pd.DataFrame(np.random.randn(2, 2))

In [12]: df
Out[12]:
          0         1
0  1.058814 -0.011675
1 -0.002627 -0.152505

In [13]: pd.options.display.float_format = '{:.2f}'.format

In [14]: df
Out[14]:
      0     1
0  1.06 -0.01
1 -0.00 -0.15

想了解更多关于Python字符串格式化的内容,可以点击这里

注意:这些数字本身并没有改变(它们没有被四舍五入):

In [15]: df.iloc[0, 0]
Out[15]: 1.058814403984879
4

你忘记把它变成字符串了:

format_percent = '{:.2f}'.format(percent_val)
#                ^      ^

另外,如果你想要得到百分比,就需要把数值乘以100。如果你用的是Python 2(我看不出来),你要么得用浮点数,要么需要加上from __future__ import division这行代码。

如果你想把数字四舍五入到小数点后两位,而不是格式化输出,可以使用round函数:

rounded = round(percent_val, 2)

这样你的输出就会是浮点数,而不是字符串,你可以继续用它进行数学运算。

撰写回答