[英]How to set a cell not column or row in a dataframe with color?
我有一个创建的具有表样式的数据框:
tableyy = final.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render()
我已经遍历了Pandas中的Coloring Cells , 有条件地更改特定单元格的背景色 , 有条件地格式化Python pandas cell和pandas数据帧中的Color单元格 ,我仍然无法在没有任何条件的情况下设置颜色而不是整个数据帧的单元格。 任何人都有任何想法,我已经尝试了这个颜色代码一个月,以便希望能收到大家的建议,谢谢。
尝试这个:
data = pd.DataFrame(np.random.randn(6, 6), columns=list('ABCDEF'))
def highlight_cells(x):
df = x.copy()
#set default color
#df.loc[:,:] = 'background-color: papayawhip'
df.loc[:,:] = ''
#set particular cell 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
t = data.style.apply(highlight_cells, axis=None)
t
@kathir:您可以在这里找到许多示例。 下面的示例是一个图形化的过大杀伤力,但总结了一些功能。 有一个“ border”属性,但在我的环境中不起作用(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)\
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.