【问题标题】:how to draw a beautiful colorful table with pandas or other package in Python?如何用 Python 中的 pandas 或其他包绘制漂亮的彩色表格?
【发布时间】:2019-09-26 05:20:27
【问题描述】:

我正在尝试画一张彩色的桌子,像这样。

这个post 提供了一种方法。

from datetime import datetime, timedelta
import pandas as pd

name = ['Diego', 'Luis', 'Vidal', 'John', 'Yusef']
id = ['b000000005', 'b000000015', 'b000000002', 'b000000011', 'b000000013']
cel = [7878, 6464, 1100, 4545, 1717]
date = pd.to_datetime(['2017-05-31 20:53:00', '2017-05-11 20:53:00', '2017-05-08 20:53:00', 
                       '2017-06-06 20:53:00', '2017-06-06 20:53:00'])

df = pd.DataFrame({'Name':name,'ID':id,'Cel':cel,'Date':date})

def color(val):
    if val < datetime.now():
        color = 'green'
    elif val > datetime.now():
        color = 'yellow'
    elif val > (datetime.now() + timedelta(days=60)):
        color = 'red'
    return 'background-color: %s' % color

df.style.applymap(color, subset=['Date'])

与该帖子完全相同的代码,产生不同的输出。

边框不见了,颜色也和帖子里的不一样。

我错过了什么?

【问题讨论】:

  • 也许使用this之类的东西可能有用?

标签: python pandas


【解决方案1】:

首先使用 pandas style 使用自定义功能设置背景颜色,然后使用 Styler.set_table_styles 设置 css 样式:

df = pd.DataFrame({'Red':[1,1,0,0,0],'Yellow':[0,0,1,0,1],'Green':[0,0,0,1,0]})
print (df)

def color(x): 
   c1 = 'background-color: green'
   c2 = 'background-color: yellow'
   c3 = 'background-color: red'
   c4 = '' 
   m = x == 1
   print (m)

   df1 = pd.DataFrame(c4, index=x.index, columns=x.columns)
   df1.loc[m['Red'], 'Red'] = c1
   df1.loc[m['Yellow'], 'Yellow'] = c2
   df1.loc[m['Green'], 'Green'] = c3
   return df1

df.style.apply(color,axis=None).set_table_styles(
   [{
       'selector': 'th',
       'props': [
           ('background-color', 'blue'),
           ('color', 'white'),
           ('border-color', 'black'),
           ('border-style ', 'solid'),
           ('border-width','1px')]
   },
    {
       'selector': 'td',
       'props': [
           ('border-color', 'black'),
           ('border-style ', 'solid'),
           ('border-width','1px')]
   },
    {'selector': '.row_heading',
          'props': [('display', 'none')]},
    {'selector': '.blank.level0',
          'props': [('display', 'none')]}])

【讨论】:

    【解决方案2】:
    1. datetime.now() 与链接的帖子 (May2017) 和您的帖子 (May2019) 不同,因此颜色不同。

    2. 您看不到这些线条,因为您的 jupyter 主题默认设置不同。该代码仅对目标单元格着色。这是我电脑上相同代码的输出:

    【讨论】:

    • 我应该选择哪个 jupyter 主题?
    • 试试this answer
    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多