Home » Python » python – pandas dataframe style – how to colormap each row individually (not whole together)-Exceptionshub

python – pandas dataframe style – how to colormap each row individually (not whole together)-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a dataframe (df) like this, using color map for styling:

#create random 30 x 30 frame
df = pd.DataFrame(np.random.randint(0, 100, (5, 20)))

df.style.background_gradient(cmap='RdYlGn_r')

enter image description here

The above code colors the dataframe over all the numbers (5 x 20 cells – smaller numbers in green, bigger numbers in red).

How can I color the small to big for each row considered individually (NOT as a whole group of 5 x 20 cells) i.e. as a 1 row x 20 cols for row 0 to 4 considered separately.

===

Example the following 2 examples for above df, highlights medians by row and column individually using apply. How can I color each row as above example for small to big numbrs.

def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

display(
    HTML("""<p style="background-color:lightblue;color:black;font-weight: bold">
             each row - median highlight
         </p>""")
)

display(df.head(5).style.apply(highlight_max, axis=1))

display(
    HTML("""<p style="background-color:lightblue;color:black;font-weight: bold">
             each col - median highlight
         </p>""")
)
display(df.head(5).style.apply(highlight_max, axis=0))

enter image description here

How to&Answers: