1

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

1
  • Could you please provide sample data, as well as the expected output, in the question? Commented Jul 28, 2020 at 10:21

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

3 Comments

And how to export this highlight because i tried and it display Styler object has no attribute 'to_csv'
Export to what? CSV, as a format, doesn't support highlighting (it doesn't have any kind of style).
so can i export to excel i think it have highlight
0

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)

1 Comment

i tried your answer but it still nothing is highlighted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.