我正在尝试构建代码,从数据帧中提取数据,应用特定的标题并删除冗余的标题,然后使用要放置在标题下的数据,我需要用纯色填充空白以便突出显示它们以供分析,然后将它们导出到新的 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 文件,但没有对文件进行格式化
最佳答案
据我了解: 假设数据框如下:
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(...)
<小时/>
输出:
关于python - 如何将 pandas 中的格式应用到导出的 Excel 文件(特别是尝试填充空白单元格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120087/