Pandas styling of rows

Hi I am trying to style a pandas data frame based on some condition and write the output to excel. I followed the solution here and got it partially done: applying-style-to-a-pandas-dataframe-row-wise.

But my output looks the one in picture. What can I do to get the original data colored instead of False and Background-color:yellow

enter image description here

This is my whole code. Can someone help me what can I do to get it right?

def highlight():
    df1,df2 = read_df();
    filterd_df = filter(df1,df2);
    styled_df = highlight_cells(df1,filterd_df,)
    with pd.ExcelWriter(r"C:\Users\test.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
        styled_df.to_excel(writer, sheet_name='result',index=False)

def highlight_cells(rows,filtered):
    c1 = 'background-color: yellow'   
    mask = rows.isin(filtered).any(axis=1)
    style_df = pd.DataFrame(False, index=rows.index, columns=rows.columns)    
    style_df.loc[mask, :] = c1
    return x: c1 if x else '')

>Solution :

If the DataFrames are aligned, you can simplify your code to directly return df2 in Styler.apply:

def highlight_cells(rows,filtered):
    c1 = 'background-color: yellow'   
    return x: np.where(df2, c1, None), axis=None)

highlight_cells(df1, df2)


def highlight_cells(rows,filtered):
    c1 = 'background-color: yellow' 
    df_style = pd.DataFrame(index=df1.index, columns=df1.columns)
    df_style[df2] = c1
    return x: df_style, axis=None)


df1 = pd.DataFrame([[1, 2], [3, 4]])
df2 = pd.DataFrame([[True, False], [False, True]])

highlight_cells(df1, df2)

enter image description here

Leave a Reply