首页 > 解决方案 > 如何在 DataFrame 中共享 style.apply 结果的位置?

问题描述

如何应用我的数据框样式的结果(数据框的位置,而不是样式本身)?

例如,我将“highlight_max”样式应用于我的数据:

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

import numpy as np
import pandas as pd
aa = pd.DataFrame([[1,2], [3,4], [1,9]])

aa.style.apply(highlight_max)

出去 :在此处输入图像描述

我想保留突出显示的单元格的位置并将其应用于另一个数据框,例如:

bb = pd.DataFrame([[7,3], [1,6], [4,2]])
bb.style.apply(**_Same_location_with_aa_**)

出去 :在此处输入图像描述

是否有任何样式选项可以获得此结果?任何意见,将不胜感激。

标签: python-3.xpandas

解决方案


据我了解,您无法导出样式格式,因为它将样式应用于第二个数据帧的最大索引。相反,您可以使用等于最大值的第一个数据帧的掩码并将其传递到函数下,np.where 如下所示:

def myf(x,color='red'):
    '''
    highlight based on the indices passed
    '''
    attr = 'background-color: {}'.format(color)
    return pd.DataFrame(np.where(mask,attr,''),index=x.index,columns=x.columns)

mask = aa.eq(aa.max())
display(aa.style.apply(myf,axis=None))
display(bb.style.apply(myf,axis=None))

在此处输入图像描述


推荐阅读