Problem with Styling withing pandas dtaframe: AttributeError: 'float' object has no attribute 'max'

Problem with Styling withing pandas dtaframe: AttributeError: 'float' object has no attribute 'max'

我试图突出显示 sliced data frame in google colab notebook 中的最小值,如下所示:

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'])

我遇到 AttributeError: 'float' object has no attribute 'max' 错误,回溯如下:

---------------------------------------------------------------------------
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'

虽然我检查了这个 & , especially this 我还是想不通。

您可以执行以下操作:

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

.applymap 应用函数 element-wise,而 .apply 应用函数到系列。