可以使用python3的数字格式将数字四舍五入到百位、千位等

2024-09-30 22:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

具体问题

我正试图打印出一张seaborn热图中单元格顶部的数字。例如,类似于:

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

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


这就产生了一个相当体面的人物,如下图所示:

heatmap, not quite ideal

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


想法

在引擎盖下,seaborn实际上只是matplotlib。我可以使用matplotlib^{} methods。在

matplotlib的文本依赖于python3的text formatting,它有方便的方法将舍入到小数点的右边,方法是做类似.2四舍五入到第一百位***,但我找不到任何东西可以往另一个方向舍入。在


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


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

谢谢!在

更新

我深入研究了^{}'s code,试图理解为什么La Rooy下面的聪明解决方案对我不起作用。在

seaborn代码中的相关行是:

^{pr2}$

但是,要使其工作,我需要能够修改我的pandasdataframe列,这意味着我需要能够调整nd.array元素的列。在

似乎有not yet any underlying ^{} method for a ^{} array,但有人努力创建一个。在

所以,我暂时不想再讨论这个问题了,我希望一旦事情解决了,我将能够采用拉鲁伊的解决方案,事情应该“奏效”。在

一旦发生这种情况,解决办法是:

>>> 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)

Tags: of方法绘图dfmatplotlib情况数字col
2条回答

您可以使用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']

或者相当于浮点数

^{pr2}$

编辑: 这个更老套的解决方案利用了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字符串。在

是的

'{:.0f}00'.format(yourNumber / 100.0)

为每一个细胞解决你的问题?在

相关问题 更多 >