gpt4 book ai didi

python - Pandas 风格 : How to highlight diagonal elements

转载 作者:太空狗 更新时间:2023-10-30 02:06:56 25 4
gpt4 key购买 nike

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

我找到了这个官方链接,他们在其中讨论了如何突出显示最大值,但是我在创建函数来突出显示对角线元素时遇到了困难。

这是一个例子:

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)

这给出了以下输出: enter image description here

我只想在对角线元素 1、3、7、11 上加亮黄色。

怎么做?

最佳答案

使用 axis=None 我们可以使用 numpy 轻松设置对角线样式(感谢@CJR)

import numpy as np
import pandas as pd

def highlight_diag(df):
a = np.full(df.shape, '', dtype='<U24')
np.fill_diagonal(a, 'background-color: yellow')
return pd.DataFrame(a, index=df.index, columns=df.columns)

df.style.apply(highlight_diag, axis=None)

enter image description here


原始的,非常hacky的解决方案

a = np.full(df.shape, '', dtype='<U24')
np.fill_diagonal(a, 'background-color: yellow')
df_diag = pd.DataFrame(a,
index=df.index,
columns=df.columns)

def highlight_diag(s, df_diag):
return df_diag[s.name]

df.style.apply(highlight_diag, df_diag=df_diag)

关于python - Pandas 风格 : How to highlight diagonal elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com