1. <tfoot id='3kWMW'></tfoot>
    2. <legend id='3kWMW'><style id='3kWMW'><dir id='3kWMW'><q id='3kWMW'></q></dir></style></legend>

      <small id='3kWMW'></small><noframes id='3kWMW'>

    3. <i id='3kWMW'><tr id='3kWMW'><dt id='3kWMW'><q id='3kWMW'><span id='3kWMW'><b id='3kWMW'><form id='3kWMW'><ins id='3kWMW'></ins><ul id='3kWMW'></ul><sub id='3kWMW'></sub></form><legend id='3kWMW'></legend><bdo id='3kWMW'><pre id='3kWMW'><center id='3kWMW'></center></pre></bdo></b><th id='3kWMW'></th></span></q></dt></tr></i><div id='3kWMW'><tfoot id='3kWMW'></tfoot><dl id='3kWMW'><fieldset id='3kWMW'></fieldset></dl></div>
        <bdo id='3kWMW'></bdo><ul id='3kWMW'></ul>
    4. Python - 使用 pandas 格式化 Excel 单元格

      时间:2023-06-06
        <bdo id='D0qcX'></bdo><ul id='D0qcX'></ul>
      • <i id='D0qcX'><tr id='D0qcX'><dt id='D0qcX'><q id='D0qcX'><span id='D0qcX'><b id='D0qcX'><form id='D0qcX'><ins id='D0qcX'></ins><ul id='D0qcX'></ul><sub id='D0qcX'></sub></form><legend id='D0qcX'></legend><bdo id='D0qcX'><pre id='D0qcX'><center id='D0qcX'></center></pre></bdo></b><th id='D0qcX'></th></span></q></dt></tr></i><div id='D0qcX'><tfoot id='D0qcX'></tfoot><dl id='D0qcX'><fieldset id='D0qcX'></fieldset></dl></div>
        • <small id='D0qcX'></small><noframes id='D0qcX'>

          <legend id='D0qcX'><style id='D0qcX'><dir id='D0qcX'><q id='D0qcX'></q></dir></style></legend>

                <tfoot id='D0qcX'></tfoot>
                  <tbody id='D0qcX'></tbody>

                本文介绍了Python - 使用 pandas 格式化 Excel 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                我有一个 pandas 数据框,如下所示.

                I have a pandas dataframe, which is something like shown below.

                我想将通过/失败"列格式化为 if Fail -->红色背景,否则绿色背景,如:

                I would like to format the column "Pass/Fail" as if Fail --> red background, else green background, like:

                我尝试使用 Pandas 进行格式化,但无法为 Excel 添加颜色.以下是代码:

                I have tried to use Pandas to do the formatting, but it fails to add color to the excel. Following is the code:

                writer = pandas.ExcelWriter(destination,engine = 'xlsxwriter')
                color = Answer.style.applymap(lambda x: 'color: red' if x == "Fail" else 'color: green',subset= pandas.IndexSlice[:,['Pass/Fail']])
                color.to_excel(writer,'sheet1')
                

                我尝试了无法安装的 StyleFrame.似乎 StyleFrame 不符合我的 python 3.6 版.

                I tried StyleFrame which failed to install. Seems that StyleFrame does not comply with my python version 3.6.

                如何根据需要格式化 Excel?

                How can I format the excel as I want?

                推荐答案

                你可以使用 conditional_format:

                df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                                   'expect':[1,2,3]})
                print (df)
                  Pass/Fail  expect
                0      Pass       1
                1      Fail       2
                2      Fail       3
                
                writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
                df.to_excel(writer, sheet_name='Sheet1')
                workbook  = writer.book
                worksheet = writer.sheets['Sheet1']
                red_format = workbook.add_format({'bg_color':'red'})
                green_format = workbook.add_format({'bg_color':'green'})
                
                worksheet.conditional_format('B2:B4', {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':     'Fail',
                                                       'format': red_format})
                
                worksheet.conditional_format('B2:B4', {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':   'Pass',
                                                       'format':  green_format})
                writer.save()
                

                更动态的解决方案 get_loc 用于 column 的位置和与 dictionary 的映射:

                More dynamic solution with get_loc for position of column and mapping with dictionary:

                import string
                
                df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                                   'expect':[1,2,3]})
                print (df)
                  Pass/Fail  expect
                0      Pass       1
                1      Fail       2
                2      Fail       3
                

                <小时>

                writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
                df.to_excel(writer, sheet_name='Sheet1')
                workbook  = writer.book
                worksheet = writer.sheets['Sheet1']
                red_format = workbook.add_format({'bg_color':'red'})
                green_format = workbook.add_format({'bg_color':'green'})
                
                #dict for map excel header, first A is index, so omit it
                d = dict(zip(range(25), list(string.ascii_uppercase)[1:]))
                print (d)
                {0: 'B', 1: 'C', 2: 'D', 3: 'E', 4: 'F', 5: 'G', 6: 'H', 7: 'I', 8: 'J',
                 9: 'K', 10: 'L', 11: 'M', 12: 'N', 13: 'O', 14: 'P', 15: 'Q', 16: 'R', 
                 17: 'S', 18: 'T', 19: 'U', 20: 'V', 21: 'W', 22: 'X', 23: 'Y', 24: 'Z'}
                
                #set column for formatting
                col = 'Pass/Fail'
                excel_header = str(d[df.columns.get_loc(col)])
                #get length of df
                len_df = str(len(df.index) + 1)
                rng = excel_header + '2:' + excel_header + len_df
                print (rng)
                B2:B4
                
                worksheet.conditional_format(rng, {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':     'Fail',
                                                       'format': red_format})
                
                worksheet.conditional_format(rng, {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':   'Pass',
                                                       'format':  green_format})
                writer.save()
                

                谢谢jmcnamara供评论和 XlsxWriter

                col = 'Pass/Fail'
                loc = df.columns.get_loc(col) + 1
                len_df = len(df.index) + 1
                
                worksheet.conditional_format(1,loc,len_df,loc, {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':     'Fail',
                                                       'format': red_format})
                
                worksheet.conditional_format(1,loc,len_df,loc, {'type': 'text',
                                                      'criteria': 'containing',
                                                       'value':   'Pass',
                                                       'format':  green_format})
                writer.save()
                

                最后一个版本的 pandas (0.20.1) 和 样式:

                Another solution with last version of pandas (0.20.1) and styles:

                df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                                   'expect':['d','f','g']})
                print (df)
                  Pass/Fail expect
                0      Pass      d
                1      Fail      f
                2      Fail      g
                
                def f(x):
                    col = 'Pass/Fail'
                    r = 'background-color: red'
                    g = 'background-color: green'
                    c = np.where(x[col] == 'Pass', g, r)
                    y = pd.DataFrame('', index=x.index, columns=x.columns)
                    y[col] = c
                    return y
                
                styled = df.style.apply(f, axis=None)
                styled.to_excel('styled.xlsx', engine='openpyxl')
                

                这篇关于Python - 使用 pandas 格式化 Excel 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                上一篇:字符串格式 JSON 字符串给出 KeyError 下一篇:python字符串格式抑制/静默keyerror/indexerror

                相关文章

              1. <i id='E1Tlp'><tr id='E1Tlp'><dt id='E1Tlp'><q id='E1Tlp'><span id='E1Tlp'><b id='E1Tlp'><form id='E1Tlp'><ins id='E1Tlp'></ins><ul id='E1Tlp'></ul><sub id='E1Tlp'></sub></form><legend id='E1Tlp'></legend><bdo id='E1Tlp'><pre id='E1Tlp'><center id='E1Tlp'></center></pre></bdo></b><th id='E1Tlp'></th></span></q></dt></tr></i><div id='E1Tlp'><tfoot id='E1Tlp'></tfoot><dl id='E1Tlp'><fieldset id='E1Tlp'></fieldset></dl></div>

                <legend id='E1Tlp'><style id='E1Tlp'><dir id='E1Tlp'><q id='E1Tlp'></q></dir></style></legend>
              2. <small id='E1Tlp'></small><noframes id='E1Tlp'>

                  <bdo id='E1Tlp'></bdo><ul id='E1Tlp'></ul>
                    <tfoot id='E1Tlp'></tfoot>