Как применить формат в pandas к экспортированному файлу Excel (в частности, пытаясь заполнить пустые ячейки) - PullRequest
1 голос
/ 26 сентября 2019

Я пытаюсь создать код, который будет извлекать данные из фрейма данных, применять определенные заголовки и удалять избыточные, после чего использовать данные, которые должны быть помещены под заголовками, которые мне нужны, чтобы заполнить пробелы сплошным цветом вЧтобы выделить их для анализа, а затем экспортировать в новый файл Excel для его распространения.

Я попробовал применить цвет, я определил цвет и попытался отформатировать в CSS, проблема в том, что, хотя кажется, что формат применяется в IDE, он не переводится в экспортированный файл Excel.

import pandas as pd
from pandas.io.formats.style import Styler
import xlsxwriter
from io import BytesIO
from flask import Flask, send_file
emt = pd.read_excel(r'C:\Users\okelly\Python Project\excel input file.xlsx', header=[0,1])# this adds the parameter into the heading allowing a search of it

#this part works
M_cols = [col for col in emt.columns if 'M' in col]
#this identifies all colums wiht M in thier subheading which is a mandoatory heading and seperates it from three other classes of headings

new_data=pd.DataFrame(emt, columns=M_cols)
#this command pulls the data and sets the list m-cols as the headers 

#this code hopefully applies a highlight to hte code in order to allow it to be anaslied
def highlight_null(val):
 if val == 'none':
      color = 'yellow'
  else : color = 'white'
 return 'background-color: %s' % color

result.style.apply(highlight_null)



result.to_excel('output1.xlsx', engine='xlsxwriter')

кажется, что никаких ошибок не возникает, и он производит файл Excel, но нет форматирования файла

1 Ответ

0 голосов
/ 26 сентября 2019

Из того, что я понимаю: если предположить, что датафрейм похож на:

df=pd.util.testing.makeMissingDataframe(density=0.5).head().reset_index(drop=True)
df.columns=['M1','A','B','M2']
print(df)

         M1         A         B        M2
0 -0.877957       NaN -2.374154 -0.585370
1       NaN       NaN       NaN       NaN
2       NaN  0.272616  0.011746 -0.344501
3       NaN       NaN       NaN       NaN
4  1.478556       NaN       NaN -0.685351

Вы можете попробовать следующую функцию:

M_cols = [col for col in df.columns if 'M' in col]
#['M1', 'M2']
def myfunc(x):
    c1='background-color: red'
    c2=''
    d_f= pd.DataFrame(np.where(x.isnull(),c1,c2),columns=x.columns,index=x.index)
    return d_f
df.style.apply(myfunc, subset=pd.IndexSlice[:, M_cols],axis=None)#.to_excel(...)

Вывод:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...