【问题标题】:dataframe to html formatter (using Flask) to be applied to all columns数据框到 html 格式化程序(使用 Flask)将应用于所有列
【发布时间】:2019-01-17 09:46:06
【问题描述】:

我正在尝试在 HTML 页面上显示我的数据框(该应用位于 Flask 框架上),作为显示的一部分,我正在使用 df.to_html 函数来执行此操作。

现在这个函数 (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html) 有 formatters 参数,它允许我一一应用(特定)列的格式。

但是,如果我需要在所有列上应用格式(列数将是动态的,所以我不能真正列出所有列名)那我该怎么做呢?

以下代码是有助于格式化 2 列(Total 和 RATE)的示例代码,但可能并非始终有 2 列完全具有这些名称。 我想为所有列应用格式。

    return render_template("ABCD.html",
                   table_name = df.to_html(
                           formatters={ 
                       "TOTAL": lambda x:'{:,.2f}'.format(x),
                        "RATE": lambda x:'{:,.2f}'.format(x)},
     bold_rows = True, border =2,  index = False, justify = 'center',  na_rep =' '))

【问题讨论】:

  • 您想对每一列应用相同的格式吗?
  • @JoshFriedlander:是的,可以的
  • @JoshFriedlander :假设我只想应用从数据框的第二列到最后一列的格式,那将如何改变?

标签: python html pandas flask


【解决方案1】:

这应该可行:

return render_template("ABCD.html",
               table_name = df.to_html(
                       formatters=[lambda x:'{:,.2f}'.format(x)] * df.shape[1],
                       bold_rows = True, border =2,  
                       index = False, 
                       justify = 'center',  
                       na_rep =' '))

【讨论】:

  • 谢谢@josh 如果我要对所有列(第一列除外)都这样做,那会怎样?再次感谢
  • 您需要为第一列指定格式并将其添加到列表中。列表的长度需要等于列数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2017-10-07
  • 2018-09-24
相关资源
最近更新 更多