Issue
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.
Solution
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.
Answered By - kelvt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.