Python 如何使用pandas为excel中的特定行添加背景色

Python 如何使用pandas为excel中的特定行添加背景色,python,pandas,Python,Pandas,我需要为特定行添加背景色。以下是条件。 1.需要在搜索图案行之前添加背景色 下面是Excel Name Depth TOTAL_AREA Category Sub Category_1 Sub Category_2 cell_type Name1 0 57.1228709 11_DDR Name2 1 0.4181432 HM N

我需要为特定行添加背景色。以下是条件。 1.需要在搜索图案行之前添加背景色

下面是Excel

Name    Depth   TOTAL_AREA  Category     Sub Category_1  Sub Category_2 cell_type
Name1   0       57.1228709  11_DDR          
Name2   1       0.4181432                                               HM
Name3   1       1.4674                                                  HM
Name4   2       0.972       23_Security  Security_Processor sp_wrapper  HM
Name5   2       0.24        23_Security  Security_Processor sp_wrapper  
Name6   2       0.2456      23_Security  Security_Processor sp_wrapper  STD
Name7   2       0.0098      23_Security  Security_Processor sp_wrapper  STD
Name8   1       0.0008984   11_DDR       SHUB               GEMNOC      STD
Name9   1       0.0006654   11_DDR       SHUB               GEMNOC      STD
Name10  1       0.000237    11_DDR       SHUB               GEMNOC      STD
Name11  1       0.0000341   02_GPU       gfx_core           gfx_core    STD
Name12  1       8.16E-05    02_GPU       gfx_core           gfx_core    STD
Name13  1       2.79E-05    08_Modem    modem_offline   modem_lmem_cluster_0    STD
Name14  1   -   0.0000498   02_GPU      gfx_core        gfx_core    
Name15  2       0.018118                
Name16  3       0.0087      23_Security  Security_Processor sp_wrapper  HM
Name17  3       0.000765    23_Security Security_Processor  sp_wrapper  HM
Name18  3       0.008653    23_Security Security_Processor  sp_wrapper  STD
需要为Name3和Name15行添加2个背景色,因为我的搜索模式是“23_安全”。 感谢您的帮助

我试过下面的脚本。仅添加指定行的背景色

代码如下:

import pandas as pd
from StyleFrame import StyleFrame, Styler
from xlrd import open_workbook
path = '<input.xlsx>'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx,'Sheet1')
sf = StyleFrame(df)

categories = ['23_Security']
book = open_workbook(path)

for sheet in book.sheets():

for rowidx in range(sheet.nrows):
    row = sheet.row(rowidx)
    for colidx, cell in enumerate(row):
         for category in categories:
               sf.apply_style_by_indexes(sf[sf['Category'] == category],styler_obj=Styler(bg_color='green'))
sf.to_excel('output.xlsx',index=False).save()
将熊猫作为pd导入
从StyleFrame导入StyleFrame、Styler
从xlrd导入打开的\u工作簿
路径=“”
xlsx=pd.ExcelFile(路径)
df=pd.read_excel(xlsx,'Sheet1')
sf=样式框(df)
类别=['23_安全']
book=打开工作簿(路径)
对于book.sheets()中的工作表:
对于范围内的行IDX(sheet.nrows):
行=工作表。行(rowidx)
对于colidx,枚举(行)中的单元格:
对于类别中的类别:
sf.按索引应用样式(sf[sf['Category']==Category],styler\u obj=styler(bg\u color='green'))
sf.to_excel('output.xlsx',index=False).save()