【问题标题】:Using a dataframe to format the style of another dataframe使用一个数据框来格式化另一个数据框的样式
【发布时间】:2019-09-19 14:34:14
【问题描述】:

我有一个 pandas 数据框,我想根据另一个相同形状/大小的数据框的值来设置格式的样式。我正在尝试使用 applymap。

这是一个例子:

t1= pd.DataFrame({'x':['A','B','C'], 'y':['C','B','D']})
t2= pd.DataFrame({'x':[0.3,0.2,0.7], 'y':[1,0.3,2]})

def color_cells(s, threshold=0.5):
    if s > threshold:
        return 'color:{0}; font-weight:bold'.format('red')
    else:
        return ''

#Tried
t1.style.applymap(t2.applymap(color_cells))

理想情况下,在 t1 中,t2 中的相应单元格>0.5,然后 t1 中的值以“红色粗体”显示。

但是,我不确定应该使用什么模式来获得这种预期的效果。

【问题讨论】:

    标签: pandas pandas-apply pandas-styles


    【解决方案1】:

    您快到了,您需要使用带有 lambda 的 apply 函数来遍历单元格。

    t1.style.apply(lambda x: t2.applymap(color_cells), axis=None)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-28
      • 2021-10-31
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多