我正在尝试使用以下脚本将时尚的数据框导出到 Excel 文件:
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4),
columns=list('BCDE'))],axis=1)
df.iloc[0, 2] = np.nan
def highlight_greater(x):
r = 'red'
g = 'gray'
m1 = x['B'] > x['C']
m2 = x['D'] > x['E']
df1 = pd.DataFrame('background-color: ', index=x.index, columns=x.columns)
#rewrite values by boolean masks
df1['B'] = np.where(m1, 'background-color: {}'.format(r), df1['B'])
df1['D'] = np.where(m2, 'background-color: {}'.format(g), df1['D'])
return df1
df.style.apply(highlight_greater, axis=None).to_excel('df.xlsx', engine='openpyxl')
它工作得很好,但是当我打开文件时,如果条件不匹配,背景就会变成黑色,有解决这个问题的想法吗?
您可以创建DataFrame
函数中用空值填充:
def highlight_greater(x):
r = 'red'
g = 'gray'
m1 = x['B'] > x['C']
m2 = x['D'] > x['E']
#if not match return empty string
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
#rewrite values by boolean masks
df1['B'] = np.where(m1, 'background-color: {}'.format(r), df1['B'])
df1['D'] = np.where(m2, 'background-color: {}'.format(g), df1['D'])
return df1
df.style.apply(highlight_greater, axis=None).to_excel('df.xlsx', engine='openpyxl')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)