将样式的熊猫数据框导出到excel

时间:2019-01-03 09:37:33

标签: python pandas pandas-styles

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

效果很好,但是当我打开文件时,如果条件不匹配,背景为黑色,那么有解决此问题的主意吗?

1 个答案:

答案 0 :(得分:2)

您可以在函数中创建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')

pic