Python Pandas - Highlighting maximum value in column

Viewed 14669

I have a dataframe produced by this code:

hmdf = pd.DataFrame(hm01)
new_hm02 = hmdf[['FinancialYear','Month']]
new_hm01 = hmdf[['FinancialYear','Month','FirstReceivedDate']]

hm05 = new_hm01.pivot_table(index=['FinancialYear','Month'], aggfunc='count')
vals1 = ['April    ', 'May      ', 'June     ', 'July     ', 'August   ', 'September', 'October  ', 'November ', 'December ', 'January  ', 'February ', 'March    ']

df_hm = new_hm01.groupby(['Month', 'FinancialYear']).size().unstack(fill_value=0).rename(columns=lambda x: '{}'.format(x))
df_hml = df_hm.reindex(vals1)

And then I have a function to highlight the maximum value in each column:

def highlight_max(data, color='yellow'):
    '''
    highlight the maximum in a Series or DataFrame
    '''
    attr = 'background-color: {}'.format(color)
    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_max = data == data.max()
        return [attr if v else '' for v in is_max]
    else:  # from .apply(axis=None)
        is_max = data == data.max().max()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)

And then this code: dfPercent.style.apply(highlight_max) produces this:

enter image description here

As you can see, only the first and last column have the correct max value highlighted.

Anyone know what is going wrong?

Thank you

4 Answers

If you are using Python 3 this should easily do the trick

dfPercent.style.highlight_max(color = 'yellow', axis = 0)

Variation highlighting max value column-wise (axis=1) using two colors. One color highlights duplicate max values. The other color highlights only the last column containing the max value.

def highlight_last_max(data, colormax='antiquewhite', colormaxlast='lightgreen'):
    colormax_attr = f'background-color: {colormax}'
    colormaxlast_attr = f'background-color: {colormaxlast}'
    max_value = data.max()
    is_max = [colormax_attr if v == max_value else '' for v in data]
    is_max[len(data) - list(reversed(data)).index(max_value) -  1] = colormaxlast_attr
    return is_max

df.style.apply(highlight_last_max,axis=1)

Easy way to color max, min, or null values in pandas.DataFrame is to uses style of pandas.DataFrame.style, which Contains methods for building a styled HTML representation of the DataFrame. Here is an example:

  • Color Max Values: your_df.style.highlight_max(color = 'green')
  • Color Min Values: your_df.style.highlight_min(color = 'red')
  • Color Null values: your_df.highlight_null(color = 'yellow')
  • If you want to apply all in the same output:
    your_df.style.highlight_max(color='green').highlight_min(color='red').highlight_null(null_color='yellow')
Related