如何共享style.apply结果在DataFrame中的位置?

问题描述 投票:0回答:2

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

例如,我将'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)

输出:enter image description here

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

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

输出:enter image description here

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

我如何应用对数据框进行样式设置的结果(数据框的位置,而不是样式本身)?例如,我将“ highlight_max”样式应用于我的数据:def highlight_max(data,color ='red'):''...

python-3.x pandas
2个回答
0
投票

用途:


0
投票

据我了解,您无法导出样式格式,因为它将样式应用于第二个数据帧的最大索引。相反,您可以对第一个数据框进行屏蔽,使其等于最大值,然后通过np.where将其传递给函数,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.