限制 for 循环中的浮点值 Python

Limiting float value in for loop Python

我正在从事银行项目,我的团队要求我将所有浮点值限制为 .2 精度。

我的dataSet.head()

目标:相对地找到所有股票的最大值

我现在的输出:

银行代码
BAC 54.900002
C 564.099976
GS 247.919998
JPM 70.080002
女士 89.300003
世界金融中心 58.520000
dtype: float64

我的预期输出:

银行代码
BAC 54.90
C 564.10
GS 247.91
JPM 70.08
女士 89.30
世界金融中心 58.52
dtype: float64

请帮我解决这个问题!

这不是一个干净的解决方案,但您可以将最高股票价格乘以 100,然后用 1 进行底数除法,然后除以 100。

这将解决您的问题。

您在打印语句中错误地使用了“{:.2f}”,您应该使用.format() 来格式化您的浮点数。

您可以使用 print("{:.2f}".format(some float)) 打印带 2 位小数的浮点数 as explained here

你可以使用 pandas.Series.round method

我有一个玩具DataFramedf:

l1        c1                           c2             
l2         a         b          c       a      b     c
0   0.066667  0.666667   6.666667  0.0002  0.002  0.02
1   0.133333  1.333333  13.333333  0.0004  0.004  0.04
2   0.200000  2.000000  20.000000  0.0006  0.006  0.06
3   0.266667  2.666667  26.666667  0.0008  0.008  0.08
df.xs('c', axis=1, level='l2').max().round(2)

结果为:

l1
c1    26.67
c2     0.08
dtype: float64

我猜你的情况

res = bank_stocks.xs('Close', axis=1, level='Stock Info').max().round(2)

将导致 Series res 由名称为 Bank Ticker 的代码索引,所需值四舍五入到小数点后两位。

根据 this answer 你可以用

打印它
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(res)

我不是一个非常高级的 python 程序员,但我应该这样做:

{:.2f}.format(max())

至少可以说,这会将 564.099976 打印为 564.09

这对我有用,可靠,没有循环

bank_stocks.xs(key='Close',axis=1,level='Stock Info').max().round(2)

O(n)^2 现在是 O(n)