【问题标题】:Highlighting multiple cells in different colors with Pandas使用 Pandas 以不同颜色突出显示多个单元格
【发布时间】:2017-05-24 03:59:26
【问题描述】:

假设我们有一个数据框,我想为不同的单元格着色:

  • 单元格['Arizona','company'](1st)['Texas','size'](1099) 为绿色。
  • 单元格['Florida','veterans'](26)['Maine','armored'](0) 为红色。

有什么好的方法吗?

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
            'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
            'deaths': [523, 52, 25, 616, 43, 234, 523, 62, 62, 73, 37, 35],
            'battles': [5, 42, 2, 2, 4, 7, 8, 3, 4, 7, 8, 9],
            'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005, 1099, 1523],
            'veterans': [1, 5, 62, 26, 73, 37, 949, 48, 48, 435, 63, 345],
            'readiness': [1, 2, 3, 3, 2, 1, 2, 3, 2, 1, 2, 3],
            'armored': [1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1],
            'deserters': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
            'origin': ['Arizona', 'California', 'Texas', 'Florida', 'Maine', 'Iowa', 'Alaska', 'Washington', 'Oregon', 'Wyoming', 'Louisana', 'Georgia']}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'deaths', 'battles', 'size', 'veterans', 'readiness', 'armored', 'deserters', 'origin'])

df = df.set_index('origin')

df.head()

(http://chrisalbon.com/python/pandas_indexing_selecting.html)

【问题讨论】:

  • 您想如何将这些数据保存到 excel、html 或其他文件中?
  • 我实际上想在 IPython Notebook 中显示数据框。

标签: python pandas highlight


【解决方案1】:

您可以将slicing in Style 与参数subset 和函数Styler.applymap 一起用于元素样式,在jupyter notebook 中运行代码:

import pandas as pd
import numpy as np

def red(val):
    color = 'red'
    return 'background-color: %s' % color

def green(val):
    color = 'green'
    return 'background-color: %s' % color

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
            'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
            'deaths': [523, 52, 25, 616, 43, 234, 523, 62, 62, 73, 37, 35],
            'battles': [5, 42, 2, 2, 4, 7, 8, 3, 4, 7, 8, 9],
            'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005, 1099, 1523],
            'veterans': [1, 5, 62, 26, 73, 37, 949, 48, 48, 435, 63, 345],
            'readiness': [1, 2, 3, 3, 2, 1, 2, 3, 2, 1, 2, 3],
            'armored': [1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1],
            'deserters': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
            'origin': ['Arizona', 'California', 'Texas', 'Florida', 'Maine', 'Iowa', 'Alaska', 'Washington', 'Oregon', 'Wyoming', 'Louisana', 'Georgia']}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'deaths', 'battles', 'size', 'veterans', 'readiness', 'armored', 'deserters', 'origin'])

df = df.set_index('origin')
print (df)

df.style.applymap(green, subset=pd.IndexSlice['Arizona':'Texas', 'company': 'size'])
        .applymap(red, subset=pd.IndexSlice['Florida':'Maine', 'veterans': 'armored'])

如果只需要更改DataFrame 中的某些值,您可以使用Styler.applyaxis=None 进行表格样式,并且该函数必须返回具有相同索引和列标签的DataFrame

def create_colors(x):
    #copy df to new - original data are not changed
    df1 = x.copy()
    #select all values to default value - no color
    df1.loc[:,:] = 'background-color: '
    #overwrite values with green and red color
    df1.loc['Arizona', 'company'] = 'background-color: green'
    df1.loc['Texas', 'size'] = 'background-color: green'
    df1.loc['Florida', 'veterans'] = 'background-color: red'
    df1.loc['Maine', 'armored'] = 'background-color: red'
    #return color df
    return df1      

df.style.apply(create_colors, axis=None)

【讨论】:

  • 谢谢耶兹瑞尔。但是,如果我不想突出显示一系列单元格,而只想突出显示上面提到的 4 个特定单元格呢?
  • 然后使用df.style.applymap(green, subset=pd.IndexSlice['Arizona', 'company']).applymap(green, subset=pd.IndexSlice['Texas', 'size']).applymap(red, subset=pd.IndexSlice['Florida', 'veterans']).applymap(red, subset=pd.IndexSlice['Maine', 'armored'])
  • 我添加了另一个更好的解决方案。如果我的回答有帮助,请不要忘记accept。谢谢。
  • 感谢 jezrael ,这正是我正在寻找的答案!
  • 如果我的回答有帮助,别忘了accept。谢谢。
【解决方案2】:

http://melissagymrek.com/python/2014/01/12/ipython-tables.html试试这个例子

from ipywidgets import *
import pandas as pd
df = pd.DataFrame({"x":[1,2,3], "y":[6,4,3], "z":["testing","pretty","tables"], "f":[0.023432, 0.234321,0.5555]})
pt = PrettyTable(df)
pt


# Set cell style using a CellStyle object
pt = PrettyTable(df, tstyle=TableStyle(theme="theme1"), center=True)
cs = CellStyle()
cs.set("background-color", "red")
cs.set("color", "white")
pt.set_cell_style(style=cs)
pt

http://melissagymrek.com/python/2014/01/12/ipython-tables.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2021-09-16
    相关资源
    最近更新 更多