[英]How do you apply a format in pandas to an exported excel file (specifically trying to fill blank cells)
我正在嘗試構建將從 dataframe 上提取數據的代碼,應用特定的標題並刪除多余的標題,然后使用要放置在標題下的數據,我需要用純色填充空白以突出顯示它們進行分析,然后將它們導出到新的 excel 文件以便傳播。
我試過應用顏色,我定義了顏色,我嘗試在 CSS 中格式化,問題是雖然格式似乎應用於 IDE,但它沒有轉換為導出的 ZC1D81AF5835844B4FDCE 文件。
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 文件,但文件沒有格式化
據我了解:假設 dataframe 就像:
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(...)
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.