Python Pandas - 突出显示列中的最大值

标签 python pandas

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

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)

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

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)

然后这段代码:dfPercent.style.apply(highlight_max) 产生这个:

enter image description here

如您所见,只有第一列和最后一列突出显示了正确的最大值。

谁知道出了什么问题?

谢谢

最佳答案

您需要将值转换为 float 以获得正确的 max,因为获取字符串的最大值 - 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)

示例:

dfPercent = pd.DataFrame({'2014/2015':['10.3%','9.7%','9.2%'],
                   '2015/2016':['4.8%','100.8%','9.7%']})
print (dfPercent)
  2014/2015 2015/2016
0     10.3%      4.8%
1      9.7%    100.8%
2      9.2%      9.7%

命令:

dfPercent.style.apply(highlight_max)

jupyter

关于Python Pandas - 突出显示列中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45606458/

相关文章:

python - 如何在 Windows8 上安装 Pygame 以使用 Python 3.3.3?

python - 使用Ctypes调用复杂的c++代码

python - Pandas 将文本文件转换为 CSV

python - 如何计算数据框行的标准偏差?

python - 每张工作表有多个数据框,每个工作簿有多个工作表

python - Python 中的 Pandas 和 NumPy+SciPy 有什么区别?

python - 如何保留在 python 的数据框中重复出现的值的第一次出现?

jquery - 谷歌应用引擎 : Browser to Server persistent connection

python - setup.cfg 使用 "Entry points must be listed in groups"声明 console_scripts 错误

具有复杂标准的 python pandas 重复数据删除