3

I have the following pandas dataframe with index "NUM":

df

I want to add color to cells using the followin dictionary:

d =  {'R1': [1,2,3,4,5,6,7,8,9,10]
  ,'R2': [3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  ,'R3': [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
  ,'R4': [11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
  ,'R5': [17,18,19,20,21,22,23,24,25,26,27,28]
}

The values in the dictionary values (lists) are the index in the dataframe. I want to add background color to the cells, for example in "R1" column color 1 to 10, in "R2" column color 3 to 20 and so on.

Thanks

1 Answer 1

2

You can try:

df.style.apply(
    lambda x: ['background-color:red' if i in d[x.name] else '' 
               for i in np.arange(len(x))+1]
)

Output:

Output

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

Comments

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.