[Python] How to color excel cells with specific values in dataframe Python

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I created a code to insert my dataframe, called df3, into an excel file.

    My code is working fine, but now I'd like to change background cells color in all cells based on value

    I tried this solution, I don't get any errors but I also don't get any cells colored

    My code:

    def cond_formatting(x):
    if x == 'OK':
    return 'background-color: lightgreen'
    elif x == 'NO':
    return 'background-color: red'
    else:
    return None

    print(pd.merge(df, df2, left_on='uniquefield', right_on='uniquefield2', how='left').drop('uniquefield2', axis=1))
    df3 = df.merge(df2, left_on='uniquefield', right_on='uniquefield2', how='left').drop(['uniquefield2', 'tournament2', 'home2', 'away2', 'result2'], axis=1)
    df3 = df3[["home","away","scorehome","scoreaway","best_bets","oddtwo","oddthree","htresult","shresult","result","over05ht","over15ht","over05sh","over15sh","over05","over15","over25","over35","over45","goal","esito","tournament","uniquefield"]]
    df3 = df3.sort_values('best_bets')

    df3.style.applymap(cond_formatting)



    # determining the name of the file
    file_name = camp + '_Last_20' + '.xlsx'

    # saving the excel
    df3.to_excel(file_name, freeze_panes=(1, 0))
    print('Tournament is written to Excel File successfully.')


    How I said, code is working but all background cells color are white (no colors) any suggestion?

    Thanks for your help

    Continue reading...

Compartilhe esta Página