【问题标题】:Change the color of text within a pandas dataframe html table python using styles and css使用样式和css更改pandas数据框html表python中文本的颜色
【发布时间】:2016-11-25 11:13:30
【问题描述】:

我有一个熊猫数据框:

arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
           'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
          ['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
                  columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])

从中打印df 的表格如下所示:

我想将“MOS”行中的所有值着色为某种颜色,并将左侧两个索引/标题列以及顶部标题行着色为与其他单元格不同的背景颜色他们。有什么想法可以做到这一点吗?

【问题讨论】:

    标签: python html css pandas dataframe


    【解决方案1】:

    使用 pandas 新的 styling 功能(自 0.17.1):

    import numpy as np
    import pandas as pd
    
    arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
               'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
              ['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples)
    df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
                      columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
    
    
    def highlight_MOS(s):
        is_mos = s.index.get_level_values(1) == 'MOS'
        return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]
    
    s = df.style.apply(highlight_MOS)
    s
    

    【讨论】:

      【解决方案2】:

      这需要几个步骤:

      首先导入HTMLre

      from IPython.display import HTML
      import re
      

      您可以通过to_html 方法获取html pandas 输出。

      df_html = df.to_html()
      

      接下来,我们将为要创建的 html 表格和样式生成一个随机标识符。

      random_id = 'id%d' % np.random.choice(np.arange(1000000))
      

      因为我们要插入一些样式,所以我们需要小心地指定这个样式只适用于我们的表格。现在让我们将其插入df_html

      df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
      

      并创建一个样式标签。这真的取决于你。我只是添加了一些悬停效果。

      style = """
      <style>
          table#{random_id} tr:hover {{background-color: #f5f5f5}}
      </style>
      """.format(random_id=random_id)
      

      最后展示一下

      HTML(style + df_html)
      

      功能一应俱全。

      def HTML_with_style(df, style=None, random_id=None):
          from IPython.display import HTML
          import numpy as np
          import re
      
          df_html = df.to_html()
      
          if random_id is None:
              random_id = 'id%d' % np.random.choice(np.arange(1000000))
      
          if style is None:
              style = """
              <style>
                  table#{random_id} {{color: blue}}
              </style>
              """.format(random_id=random_id)
          else:
              new_style = []
              s = re.sub(r'</?style>', '', style).strip()
              for line in s.split('\n'):
                      line = line.strip()
                      if not re.match(r'^table', line):
                          line = re.sub(r'^', 'table ', line)
                      new_style.append(line)
              new_style = ['<style>'] + new_style + ['</style>']
      
              style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))
      
          df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
      
          return HTML(style + df_html)
      

      像这样使用它:

      HTML_with_style(df.head())
      

      HTML_with_style(df.head(), '<style>table {color: red}</style>')
      

      style = """
      <style>
          tr:nth-child(even) {color: green;}
          tr:nth-child(odd)  {color: aqua;}
      </style>
      """
      HTML_with_style(df.head(), style)
      

      学习 CSS 并发疯!

      【讨论】:

      • 我以前从未使用过 HTML,所以如果这是一个简单的问题,我深表歉意,但是当我在 ipython 笔记本单元格中键入这个完全相同的函数时,表格看起来与以前完全相同。我还需要做些什么或更改以使其以不同的颜色显示吗?
      • 我可以问你一个愚蠢的问题 - 如何在 Jupyter 中将输出单元格保存为图片?我对 Jupyter 的经验几乎为零,但还想不通……谢谢!
      • @MaxU 我每次都截图
      • @piRSquared,谢谢!我认为在 Jupyter 中找不到一种简单的魔法方法...... :-D
      • @MaxU Command + Control + Shift + 4:使我能够拖动一个矩形并将屏幕截图放入剪贴板。 OS X
      猜你喜欢
      • 1970-01-01
      • 2019-02-06
      • 2022-06-25
      • 2015-11-18
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多