您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

一个问题,您需要将值转换为浮点数以确保正确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)

朱皮特

python 2022/1/1 18:35:57 有232人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶