6

I'm trying to export a stylish data frame to an Excel file using the script below:

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

It works well, but when I open the file the background is black when the condition does not match, an idea to solve this problem?

ouroboros1
  • 9,113
  • 3
  • 7
  • 26
Localhost
  • 95
  • 2
  • 5

1 Answers1

6

You can create DataFrame filled by empty values in function:

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

pic

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252