VS Code中Jupyter Notebook实现Gain标绿Loss标红的表格样式
问题描述
我正在为技术指标创建表格,需同步高亮信号时长及信号的gain或loss状态。我有一列名为Bull的字段,值为'gain'或'loss'。请问如何在VS Code的Jupyter Notebook中使用样式将gain值标绿、loss值标红?
我尝试了以下代码,但无法正常显示表格:
def cts(x): c1 = 'color: red' c2 = 'color: green' c3 = 'color: white' if 'Gain' in x['Bull - Long Position']: return c3,c1,c1 elif 'Loss' in x['Bull - Long Position']: return c3,c2,c2 else: return c3,c3,c3 df = df.reset_index(drop=True).style.apply(cts, subset=['Strategy', 'Age', 'Long short indicator'], axis=1)
解决方案
你的代码存在两个核心问题:
- 字段名不匹配:你提到的目标列是
Bull,但代码里判断的是'Bull - Long Position' - 样式逻辑偏离需求:你需要的是高亮
Bull列的gain/loss值,但代码却给Strategy、Age等列设置样式,逻辑不对应
针对你的需求,推荐两种简单可行的实现方式:
方式一:单独高亮Bull列
如果仅需要给Bull列的gain标绿、loss标红,用applymap直接针对列处理最简洁:
def color_bull_value(val): if val == 'gain': return 'color: green' elif val == 'loss': return 'color: red' return '' # 其他值保持默认样式 # 对Bull列应用样式,用新变量存储样式对象,避免覆盖原DataFrame styled_df = df.reset_index(drop=True).style.applymap(color_bull_value, subset=['Bull']) # 在Notebook中运行此行即可渲染带样式的表格 styled_df
方式二:同步高亮关联列
如果需要根据Bull列的值,同步高亮其他列(比如信号时长列Age),可以用apply按行处理:
def highlight_related_cols(row): # 初始化所有列的样式为空 style_list = [''] * len(row) # 获取Bull列的索引位置 bull_col_idx = row.index.get_loc('Bull') # 获取需要同步高亮的列索引,比如Age age_col_idx = row.index.get_loc('Age') if row['Bull'] == 'gain': style_list[bull_col_idx] = 'color: green' style_list[age_col_idx] = 'color: green' elif row['Bull'] == 'loss': style_list[bull_col_idx] = 'color: red' style_list[age_col_idx] = 'color: red' return style_list # 应用样式到所有列,或通过subset指定目标列 styled_df = df.reset_index(drop=True).style.apply(highlight_related_cols, axis=1) # 渲染表格 styled_df
注意:不要将样式对象直接赋值给原df变量,否则原DataFrame会被覆盖成样式对象,后续无法正常使用原数据。
内容的提问来源于stack exchange,提问作者Laura Nayiga
相关产品推荐
相关产品推荐

