将样式化的 pandas 数据框导出到 excel

Export styled pandas data frame to excel

我正在尝试使用下面的 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')