本文介绍了 pandas 风格:如何突出对角线元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用df.style方法突出显示熊猫数据框的对角线元素.

I was wondering how to highlight diagonal elements of pandas dataframe using df.style method.

我找到了这个官方链接,他们在其中讨论了如何突出显示最大值,但是我很难创建功能来突出显示对角线元素.

I found this official link where they discuss how to highlight maximum value, but I am having difficulty creating function to highlight the diagonal elements.

这里是一个例子:

import numpy as np
import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})

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]

df.style.apply(highlight_max)

这给出了以下输出:

This gives following output:

我只希望在对角线元素1,3,7,11上有一个黄色突出显示.

I am wanting a yellow highlight across the diagonal elements 1,3,7,11 only.

该怎么做?

推荐答案

另一个答案很好,但是我已经这样写了.

The other answer is pretty good but I already wrote this so....

def style_diag(data):
    diag_mask = pd.DataFrame("", index=data.index, columns=data.columns)
    min_axis = min(diag_mask.shape)
    diag_mask.iloc[range(min_axis), range(min_axis)] = 'background-color: yellow'
    return diag_mask

df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})
df.style.apply(style_diag, axis=None)

这篇关于 pandas 风格:如何突出对角线元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 22:06