如何有条件地格式化数据框

时间:2020-07-06 13:41:59

标签: python css pandas

我有一个没有特定列数和行数的数据框。我希望基于3色标的条件格式基于excel上的值。值没有特殊条件

enter image description here

我已经创建了一个html表并设置了样式,但是它的呈现效果并不理想。

 cm = colors.LinearSegmentedColormap.from_list("3_colors", ["mediumseagreen", "khaki", "salmon"])

styles = [ dict(selector="th", props=[("background-color", "#FFBC00")]),
           dict(selector ='tr', props=[("background-color", cm), ('font-weight', 'bold')] )

html1 = df.style.set_table_styles(styles).background_gradient(cmap = cm).render()

我是否有可能实现目标。任何建议都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

thresholds = [50,75]
def colorize(a,thresholds=thresholds):
    if a < thresholds[0]: 
        return 'background-color: green'
    elif a<thresholds[1]:
        return 'background-color: orange'
    else:
        return 'background-color: red'


df.style.applymap(colorize, thresholds=thresholds)

输出:

enter image description here

答案 1 :(得分:0)

使用自定义样式器功能!它们使您可以广泛地控制数据框样式:

制作随机数据帧:

df = pd.DataFrame.from_records((np.random.random((5,5))*10).round(2))

定义样式器功能:

def styler(x):
    if x < 3:
        return 'background: red'
    elif x < 6:
        return 'background: green'
    else:
        return 'background: blue'

应用样式器功能:

df.style.applymap(styler)

结果: A styled DataFrame, conditionally formatted by cell value!