我正在构建两个数据框之间的差异,并希望将它们保存到 excel 中(灵感来自这里的一个很好的答案):
def highlight_diff(data, color='orange'):
attr = 'background-color: {}'.format(color)
other = data.xs('Original', axis='columns', level=-1)
return pd.DataFrame(np.where(data.ne(other, level=0), attr, ''),
index=data.index, columns=data.columns)
在这一点上,如果我data_swapped.style.apply(highlight_diff, axis=None)
在 JupyterLab 中查看,它看起来会很棒——第二组中的不同列都有背景。
当您尝试将其保存到 excel 时,它将失败:
writer = pd.ExcelWriter('diff.xls')
data_swapped.style.apply(highlight_diff, axis=None).to_excel(writer, 'Sheet1')
writer.save()
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xlwt/Style.py in _parse_strg_to_obj(strg, obj, parse_dict, field_sep, line_sep, intro_sep, esc_char, debug) 636 结果 = parse_dict.get(section) 637 if result is None: --> 638 raise EasyXFCallerError('section %r is unknown' % section) 639 if isinstance(result, dict): 640 break
EasyXFCallerError:“填充”部分未知
我有点想xlwt
对样式标签和颜色名称使用不同的转换,并认为我会作弊:
attr = 'fore_color: light_yellow'
它会删除异常,但生成的 excel 没有我正在寻找的样式。这种样式方法是否可重复用于 excel?