我正在尝试使用scrpit波纹管将时尚的数据框导出到exel文件

  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')


python - 将样式化的 Pandas 数据框导出到Excel-LMLPHP

10-05 19:07