Export styled pandas data frame to excel

元气小坏坏 提交于 2020-06-27 15:21:56

问题


I'm trying to export a stylish data frame to an exel file using the scrpit bellow

  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 ?


回答1:


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



来源:https://stackoverflow.com/questions/54019597/export-styled-pandas-data-frame-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!