Search code examples
pythondataframehighlight

how to highlight rows using dataframe and python based on value in a cell?


I want to highlight records in the dataframe and csv files based on the value on a cell ?

i tried to create a function and apply this function on the dataframe but it did not highlight any record.

enter image description here

the output must be :

enter image description here

code:

def_test_twtr_preds= pd.read_excel(path,names=col_names)


    def highlight_sentiment(status):
        if status == "Positive":
            return ['background-color: yellow']
        else:
            return ['background-color: white']
    
    def_test_twtr_preds.style.apply(highlight_sentiment,axis =1)

where is the error ??


Solution

  • Here's a solution that works (demonstrated with synthetic data):

    df  = pd.DataFrame({"a": [1, 2, 3], "status": ["Negative", "Positive", "Positive"]})
    
    def highlight_sentiment(row):
        if row["status"] == "Positive":
            return ['background-color: yellow'] * len(row)
        else:
            return ['background-color: white'] * len(row)
        
    df.style.apply(highlight_sentiment, axis=1)
    

    The output is:

    enter image description here

    To export to Excel, do the following:

    df = df.style.apply(highlight_sentiment, axis=1)
    df.to_excel("my_file.xlsx")