【问题标题】:Add thousands separator with comma at IPython.display HTML在 IPython.display HTML 处添加带逗号的千位分隔符
【发布时间】:2017-04-11 02:13:39
【问题描述】:

我的目标是使用 Python.display 创建一个数据框,其中包含格式化的值,这样每个值都有一个逗号分隔符来表示每千位。例如,我试图从这些格式化数据框中的所有值:

进入这些:

我一直在查看herehere,但我仍然无法进行格式化。有没有人可以解决这个问题?

这是目前为止的代码:

import pandas as pd
from IPython.display import HTML

styles = [
    hover(),
    dict(selector = "th",
         props = [("font-size", "110%"),
                  ("text-align", "left"),
                  ("background-color", "#cacaca")
                 ]
        )
    ]

column_01 = [2000000000, 21000000, 3000]
df = pd.DataFrame(column_01)
html = (df.style.set_table_styles(styles))

'{0:,}'.format(100000000)

html

【问题讨论】:

  • 你可以将数字转换为字符串df[0] = df[0].apply(lambda x: '{0:,}'.format(x))
  • 你可以将数字转换为浮点数df[0] = df[0].astype(float),然后你可以设置pd.options.display.float_format = '{:,.0f}'.format

标签: python dataframe ipython


【解决方案1】:

Pandas 使用 pandas.formats.format.IntArrayFormatter 中的硬编码格式来格式化字符串。你需要用你自己的方法“猴子补丁”。看这里:How to format IPython html display of Pandas dataframe?

【讨论】:

  • 感谢您的参考,确实有效。因此,根据您给定链接中的代码,我将fmrt 变量添加到我的代码中,如下所示:html = (df.style.set_table_styles(styles).format(frmt)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多