价值观: 预算= 11,000 实际= 10,000 variance =预算 - 实际(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%格式化为数字而不是字符串,以便稍后进行计算?
答案 0 :(得分:3)
你忘了写一个字符串:
format_percent = '{:.2f}'.format(percent_val)
# ^ ^
另外,如果你想要一个百分比,你需要乘以100,如果你是Python 2(我不能告诉你),你要么需要使用浮点数或from __future__ import division
。
如果你想将数字舍入两位小数,而不是创建格式化输出,那么round
函数就是:
rounded = round(percent_val, 2)
然后你的输出将是一个浮点而不是一个字符串,你可以继续用它来计算数学。
答案 1 :(得分: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的字符串格式here。
注意:数字本身不受影响(它们没有被舍入):
In [15]: df.iloc[0, 0]
Out[15]: 1.058814403984879
答案 2 :(得分:0)
如果您决定使用pandas和df,如果您不介意将所有pd数据设置为特定精度,则此处为quick method,并且您可以看到数据仍然可以以其原始精度使用。
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