简体   繁体   English

熊猫样式中每列的颜色不同

[英]Different color for each column in pandas style

I have a dataframe with several columns and a list with colors associated with each column. 我有一个包含几列的数据框,以及一个与每列关联的颜色的列表。 I want to highlight the non-blank cells in each column with the associated color. 我想用相关的颜色突出显示每列中的非空白单元格。

I've tried iterating over the columns in various ways. 我尝试过以各种方式遍历列。 The closest thing to success was to put a for loop in the styling function and apply it within a for loop. 与成功最接近的事情是在样式函数中放置一个for循环,并将其应用于for循环中。 This correctly highlights the last column, but not the rest. 这会正确突出显示最后一列,而不突出显示其余的列。

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])

you can do this as below: 您可以按照以下步骤进行操作:

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)

在此处输入图片说明

Try this: 尝试这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM