0

So what I'm trying to do is, based on content in column, set color for whole row (view image for context)

Example: If data in column Status is "Finished", then the color for that row is blue; for "Reading" the color is green etc.

My code:

import pandas as pd
df = pd.read_csv("data.txt", delimiter='|')

def colored_text():
    if df.loc[df['Status'] == 'Reading']:
        return 'color: green'
    else:
        return 'color: yellow'
    

df.style.applymap(colored_text)

print(df)

Output of this is only white-colored table. I've also tried df.style.apply(colored_text) with the same result.

At that point I was lost, so I tried df.style.set_properties(color="green") instead of .apply(colored_text) and again, the output was the same white-colored table.

So now I'm not even sure if code in def colored_text(): is correct or not

1
  • You have print(df) that's always going to give you plaintext console output... If you want to see the display of a pandas styler you'll need to be in a dynamic HTML environment like Jupyter Notebook or Google Colab, or export to an environment which supports styling like Excel, LaTeX, or HTML. Commented Mar 21, 2022 at 22:29

1 Answer 1

1

Use:

import pandas as pd
df = pd.DataFrame({'status': ['Reading', 'Writing', 'Reading'], 'other col': range(3)})
n = len(df.columns)
df.style.apply(lambda x: ["background-color: red"]*n if x['status']== 'Reading' else ["background-color: white"]*n, axis = 1)

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Didn't work. I got same output as always, color changes didn't apply. I guess that the problem is somewhere else ?
You can see that I produced the results. maybe your packages or python version differs.

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.