Pyleb Pyl3b
Pyleb Pyl3b

Reputation: 173

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 ??

Upvotes: 1

Views: 2723

Answers (2)

Roy2012
Roy2012

Reputation: 12523

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

Upvotes: 1

Imran
Imran

Reputation: 885

The one thing that can be you are not sending the input argument status when calling the function.

def_test_twtr_preds.style.apply(highlight_sentiment("positive"),axis =1)

Upvotes: 0

Related Questions