gpt4 book ai didi

python - 可以使用 Python 3 的数字格式将数字四舍五入到百、千等

转载 作者:行者123 更新时间:2023-11-28 16:26:48 25 4
gpt4 key购买 nike

具体问题

我正在尝试打印出 seaborn 热图中单元格顶部的数字。例如,像这样的东西:

ax = sns.heatmap(flights, annot=True, fmt=",")

(这直接取自 seaborn's documentation,调整为 Python 3 友好。因此,如果您导入 seaborn,您可以开箱即用地运行相同的示例。)


这会生成一个相当可观的数字,如下图所示:

heatmap, not quite ideal

但是,我希望看到数字四舍五入到最接近的百位。换句话说,我想看到像 171 这样的数字写成 200,315 写成 300 等等。


想法

在幕后,seaborn 实际上只是 matplotlib。我可以使用 matplotlibtext methods .

matplotlib 的文本依赖于 Python 3 的 text formatting ,它有方便的方法将舍入到小数点的右边,通过像 .2 舍入到百位*** ***,但我找不到任何东西可以转向另一个方向。


我可以在将数字推送到绘图之前简单地四舍五入,但这实际上会改变绘图数据本身,我宁愿避免这种情况。因此,我希望我传递给绘图的基础数字保持不变,同时仍然能够很好地打印内容。


据我所知,做到这一点的唯一方法是找到一种巧妙的方式来格式化事物。有办法吗?

谢谢!

更新

我进一步研究了 seaborn's code ,试图理解为什么 La Rooy 下面的聪明解决方案对我不起作用。

seaborn 代码中的相关行是:

val = ("{:" + self.fmt + "}").format(val)

但是,要使其正常工作,我需要能够更改我的 pandas 数据框列,这意味着我需要能够调整 nd 的列。数组 元素。

好像有not yet any underlying .__format__ method for a numpy array , 但正在努力创造一个。

因此,我暂时不会再追究这个问题,并希望一旦事情自行解决,我将能够采用 La Rooy 的解决方案并且事情应该“有效”。

一旦发生这种情况,解决方案将是:

>>> class rndarray(np.ndarray):
... def __format__(self, spec):
... return np.ndarray.__format__(int(round(self, -2)), spec)
...
>>> df['<col_of_interest>'] = map(rndarray, df['<col_of_interest.'])

或者,如果这不起作用,则:

>>> df['<col_of_interest>'].values = map(rndarray, df['<col_of_interest.'].values)

最佳答案

您可以使用 int 的子类并根据需要定义 __format__

>>> class rint(int):
... def __format__(self, spec):
... return int.__format__(int(round(self, -2)), spec)
...
>>> raw_data = [111, 22222, 33333]
>>> data = map(rint, raw_data)
>>> [format(x, ',') for x in data]
['100', '22,200', '33,300']

或者等价于花车

>>> class rfloat(float):
... def __format__(self, spec):
... return float.__format__(round(self, -2), spec)
...
>>> raw_data = [111.11, 22222.22, 33333.33]
>>> data = map(rfloat, raw_data)
>>> spec = ',.0f'
>>> [format(x, spec) for x in data]
['100', '22,200', '33,300']

编辑:这个更 hacky 的解决方案利用 val = ("{:"+ self.fmt + "}").format(val) 行。当然,如果实现发生变化,这可能会中断。

class Fmt(str):
def __add__(self, other):
return Fmt(str.__add__(self, other))
def __radd__(self, other):
return Fmt(str.__add__(other, self))
def format(self, *args):
return str.format(self, *(int(round(x, -2)) for x in args))

ax = sns.heatmap(flights, annot=True, fmt=Fmt(","))

更好的是能够传递 Formatter() 而不仅仅是 fmt 字符串。

关于python - 可以使用 Python 3 的数字格式将数字四舍五入到百、千等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35946819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com