1

I have a dataframe:

df = pd.DataFrame({'grp':['A', 'A', 'B', 'B', 'B'], 'pos' : [1, 1, 1, 1, 2]})

>>> df
  grp  pos
0   A    1
1   A    1
2   B    1
3   B    1
4   B    2

I would like to set background color for the same values in each column. For example, in column grp, first two values AA should have background color 1, and BBB background color 2. In pos column, 1111 should have color x, 2 color y.

I tried to construct a dataframe with colors:

df_colors = pd.DataFrame({'grp':['#1d77ab', '#1d77ab', '#1a7899', '#1a7899', '#1a7899'], 'pos' : ['#1d77ab', '#1d77ab', '#1d77ab', '#1d77ab', '#167a7e']})

>>> df_colors
       grp      pos
0  #1d77ab  #1d77ab
1  #1d77ab  #1d77ab
2  #1a7899  #1d77ab
3  #1a7899  #1d77ab
4  #1a7899  #167a7e

If I have colors in dataframe how to apply style to dataframe df with colors in dataframe df_colors?

Regards.

1 Answer 1

1

Use Styler.apply with add background-color, only necessary same index and columns names of both DataFrames:

(df.style.apply(lambda x: 'background-color: ' + df_colors, axis=None)
   .to_excel('styled.xlsx', engine='openpyxl', index=False))
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.