[英]Python Pandas style highlight specific cells for each column with different condition
[英]Different color for each column in pandas style
我有一個包含幾列的數據框,以及一個與每列關聯的顏色的列表。 我想用相關的顏色突出顯示每列中的非空白單元格。
我嘗試過以各種方式遍歷列。 與成功最接近的事情是在樣式函數中放置一個for循環,並將其應用於for循環中。 這會正確突出顯示最后一列,而不突出顯示其余的列。
df=pd.DataFrame({'a':[1,2,3,4],'b':['','',1,''],'c':['a','b','c','']})
df_column_colors=['red','blue','green']
def highlight_cells(value):
if value=='':
background_color=None
else:
for v in range(len(df_column_colors)):
background_color=str(df_column_colors[v])
return 'background-color: %s' % background_color
for i in range(len(df.columns)):
df2=df.style.applymap(highlight_cells,subset=df.columns[i])
您可以按照以下步驟進行操作:
d= dict(zip(df.columns,['background-color:'+i for i in df_column_colors]))
#{'a': 'background-color:red', 'b': 'background-color:blue', 'c': 'background-color:green'}
def mycolor(x):
s=pd.DataFrame(d,index=x.index,columns=x.columns)
df1=x.mask(x.replace('',np.nan).notna(),s)
return df1
df.style.apply(mycolor,axis=None)
嘗試這個:
df = pd.DataFrame({'a':[1,2,3,4],'b':['','',1,''],'c':['a','b','c','']})
df_column_colors=['red','blue','green']
def apply_color(cells):
color = df_column_colors[df.columns.get_loc(cells.name)]
colors = []
for cell in cells:
if cell == '':
colors.append('')
else:
colors.append('background-color: %s' % color)
return colors
df.style.apply(apply_color)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.