Python Pandas - 列中最大值的强调

2024-10-01 09:36:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由这个代码生成的数据帧:

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)

然后我有一个函数来突出显示每列中的最大值:

^{pr2}$

然后这个代码:dfPercent.style.apply(highlight_max)生成了:

enter image description here

如您所见,只有第一列和最后一列高亮显示正确的“最大值”。在

有人知道出什么问题了吗?在

谢谢你


Tags: 数据dataframedfnew代码生成pdhmmonth
1条回答
网友
1楼 · 发布于 2024-10-01 09:36:14

为了正确的max,您需要将值转换为float,因为get max value of strings-9更像是1

def highlight_max(data, color='yellow'):
    '''
    highlight the maximum in a Series or DataFrame
    '''
    attr = 'background-color: {}'.format(color)
    #remove % and cast to float
    data = data.replace('%','', regex=True).astype(float)
    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)

样本

^{pr2}$

jupyter

相关问题 更多 >