0

I was trying to highlight minimum values within sliced data frame in google colab notebook as below:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

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]


#def highlight_max(s, props=''):
#    return np.where(s == np.nanmax(s.values), props, '')

dff = pd.DataFrame({'A': np.linspace(1, 10, 10)})
dff = pd.concat([dff, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    applymap(highlight_max,           subset=['B',  'C',    'D'])

I face AttributeError: 'float' object has no attribute 'max' error with following traceback:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

13 frames
<ipython-input-2-2c6ddd2b019e> in highlight_max(s)
     12     highlight the maximum in a Series yellow.
     13     '''
---> 14     is_max = s == s.max()
     15     return ['background-color: yellow' if v else '' for v in is_max]
     16 

AttributeError: 'float' object has no attribute 'max'

Although I checked this post & post2, especially this post with similar error I couldn't figure out yet.

1 Answer 1

0

Here's what you can do:

dff.style.\
    applymap(color_negative_red ,     subset=['B',  'C',    'D']).\
    apply(   highlight_max,           subset=['B',  'C',    'D'])

.applymap applies a function element-wise, whereas .apply applies a function to the series.

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

2 Comments

Any idea how can I modify def highlight_max so that it shows max value bold &highlighted by yellow?
You may try returning this in the highlight_max function: 'background-color: yellow; font-weight: bold'

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.