使用其他列在Pandas中进行条件样式 [英] Conditional Styling in Pandas using other columns

查看:52
本文介绍了使用其他列在Pandas中进行条件样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过,似乎无法在任何地方找到答案,因此希望有可能.我有一个数据框,为简单起见,我将在下面包括一个缩写版本.我想做的是应用自定义公式进行样式设置,或根据另一列中的值对一个特定的列进行样式设置.

以这个为例,我想突出显示当前"列的单元格,其中该行的差异">历史标准开发".

我已经探索了style.apply方法,但似乎找不到一种有效的方法.任何帮助将不胜感激.

谢谢!

解决方案

您可以通过

I've searched and can't seem to find an answer on this anywhere, so hopefully it's possible. I have a dataframe, for simplicity I'll include an abbreviated version below. What I'd like to do is apply a custom formula for styling, or style one particular column based on the values in another column.

Using this as an example, I'd like to highlight the Current column's cells where the Diff > Historic Standard Dev in that row.

I've explored the style.apply approaches, but can't seem to find one that works. Any help would be greatly appreciated.

Thanks!

解决方案

You can create DataFrame of styles by Styler.apply:

def select_col(x):
    c1 = 'background-color: red'
    c2 = '' 
    #compare columns
    mask = x['Diff'] > x['HistoricStandardDev']
    #DataFrame with same index and columns names as original filled empty strings
    df1 =  pd.DataFrame(c2, index=x.index, columns=x.columns)
    #modify values of df1 column by boolean mask
    df1.loc[mask, 'Current'] = c1
    return df1

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

这篇关于使用其他列在Pandas中进行条件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆