1

I'm trying to create a dataframe that incorporates a rule where cells are highlighted depending on their value. I've done this using pandas.style (code for a simplified dataframe below).

y = pd.DataFrame({'A':[2,4,6,1,4,7],
                 'B':[9,5,3,6,2,5],
                 'C':[0,6,3,5,6,2]})

index_max = pd.Series([2,5,2,7,3,4])
column_max = pd.Series([1,5,7], index=['A', 'B', 'C'])

def highlight_(s):
    to_highlight = (s > index_max) & (s > column_max.loc[s.name])
    return ['background-color: yellow' if v else '' for v in to_highlight]

y.style.apply(highlight_)

This works but the dataframe I'm using is quite large and has multi-indexing, so I wanted to make it more presentable. I found the below CSS snippet that uses the magic function to apply a format that I liked (source: https://medium.com/analytics-vidhya/5-css-snippets-for-better-looking-pandas-dataframes-ad808e407894)

%%HTML
<style>.dataframe th{
background: rgb(255,255,255);
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(236,236,236,1) 100%);
padding: 5px;
color: #343434;
font-family: monospace;
font-size: 110%;
border:2px solid #e0e0e0;
text-align:left !important;
}.dataframe{border: 3px solid #ffebeb !important;}</style>

enter image description here

The problem is that I can't find a way to combine the two. I either get a style object with just the highlighting rule applied or the original dataframe with the nice new html formatting but that doesn't apply the highlighting rule. I'm hoping there's a way to combine html and the styler to achieve an output with BOTH, but I don't really know where to start.

Any help would be massively appreciated!

3
  • This question seems interesting. At first, I believed that there is a way of importing css into a style object so it would be easy to merge with another. But googling "pandas style load css" yielded only irrelevant results. Does the concept of "style objects" even exist at all? If not, how is merging possible? I wonder. Commented Oct 13, 2020 at 17:52
  • Have you checked this post? stackoverflow.com/questions/49324569/… Commented Oct 13, 2020 at 18:39
  • Thank you so much for that link! I followed the principles and it worked beautifully! Commented Oct 15, 2020 at 17:35

0

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.