如何用颜色设置数据框中的单元格而不是列或行? [英] How to set a cell not column or row in a dataframe with color?

查看:60
本文介绍了如何用颜色设置数据框中的单元格而不是列或行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建的具有表格样式的数据框:

  tableyy = final.style.set_table_attributes('border =" class ="dataframe table table-hover table-bordered"').set_precision(10).render() 

我已经经历过

I have a dataframe with table style that I created :

 tableyy = final.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render()

I have go through this Coloring Cells in Pandas , Conditionally change background color of specific cells, Conditionally format Python pandas cell, and Colour cells in pandas dataframe, I still not able to set a cell with color not the whole dataframe without any condition. Anyone have any ideas, I try this color code for one months already so hope can receive advise from anyone of you guys, thanks.

解决方案

@kathir: you may find many examples here. My example below is a graphical over-kill but summarizes some features. There is a 'border' property but it did not work in my environment (Jupyter).

import pandas as pd
import numpy as np

def highlight_single_cells(x):
    df = x.copy()
    df.loc[:,:] = '' 
    #set particular cells colors
    df.iloc[0,0] = 'background-color: red'
    df.iloc[1,1] = 'background-color: orange'
    df.iloc[2,2] = 'background-color: yellow'
    df.iloc[3,3] = 'background-color: lightgreen'
    df.iloc[4,4] = 'background-color: cyan'
    df.iloc[5,5] = 'background-color: violet'
    return df

def bold_single_cells(x):
    df = x.copy()
    df.loc[:,:] = '' 
    #set particular cells bold
    df.iloc[0,0] = 'font-weight: bold'
    df.iloc[1,1] = 'font-weight: bold'
    df.iloc[2,2] = 'font-weight: bold'
    df.iloc[3,3] = 'font-weight: bold'
    df.iloc[4,4] = 'font-weight: bold'
    df.iloc[5,5] = 'font-weight: bold'
    return df

def color_negative_red(val):
    #--- colors the + and the - values
    color = 'blue' if val < 0 else 'black'
    return 'color: %s' % color

def highlight_max(s):
    #---- highlight the maximum in a column
    is_max = s == s.max()
    return ['background-color: chartreuse' if v else '' for v in is_max]

#--- generate data ----
x = np.linspace(0.0, 0.998, 6)
xx,yy = np.meshgrid(x,x)
df =  pd.DataFrame(xx*yy-0.3, columns=list('ABCDEF'))

#--- apply the styles you want ----
df.style\
    .set_caption('My pandas sheet with a caption')\
    .background_gradient(cmap='Pastel2')\
    .applymap(color_negative_red)\
    .apply(highlight_max)\
    .apply(highlight_single_cells, axis=None)\
    .set_properties(**{'max-width': '80px',\
                       'font-size': '15pt', \
                       'border-color': 'black'})\
    .apply(bold_single_cells, axis=None)\
    .set_precision(3)\

这篇关于如何用颜色设置数据框中的单元格而不是列或行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆