将条件格式应用于熊猫数据框中的excel列

问题描述 投票:1回答:1

我正在尝试制作具有多个工作表的excel文档,并应用条件格式来选择工作表中的列,但是,由于某些原因,当我打开工作表时,我无法获得要应用的条件格式。

newexcelfilename= 'ResponseData_'+date+'.xlsx'
exceloutput = "C:\\Users\\jimbo\\Desktop\\New folder (3)\\output\\"+newexcelfilename

print("Writing to Excel file...")
# Given a dict of pandas dataframes
dfs = {'Tracts': tracts_finaldf, 'Place':place_finaldf,'MCDs':MCD_finaldf,'Counties': counties_finaldf, 'Congressional Districts':cd_finaldf,'AIAs':aia_finaldf}

writer = pd.ExcelWriter(exceloutput, engine='xlsxwriter')
workbook  = writer.book
## columns for 3 color scale formatting export out of pandas as text, need to convert to 
number format.
numberformat = workbook.add_format({'num_format': '00.0'})
## manually applying header format
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': False,
    'align': 'left',
    })


for sheetname, df in dfs.items():  # loop through `dict` of dataframes
    df.to_excel(writer, sheet_name=sheetname, startrow=1,header=False,index=False)  # send df to writer
    worksheet = writer.sheets[sheetname]  # pull worksheet object
    for col_num, value in enumerate(df.columns.values):
        worksheet.write(0, col_num, value, header_format)
    for idx, col in enumerate(df):  # loop through all columns
        series = df[col]
        col_len = len(series.name)  # len of column name/header
        worksheet.set_column(idx,idx,col_len)
        if col in ['Daily Internet Response Rate (%)',
                   'Daily Response Rate (%)',
                   'Cumulative Internet Response Rate (%)',
                   'Cumulative Response Rate (%)']:
            worksheet.set_column(idx,idx,col_len,numberformat)
        if col == 'DATE':
            worksheet.set_column(idx,idx,10)
        if col == 'ACO':
            worksheet.set_column(idx,idx,5)
    ## applying conditional formatting to columns which were converted to the 
    numberformat
    if worksheet == 'Tracts':
        worksheet.conditional_format('E2:H11982', {'type':'3_color_scale',
                                    'min_color': 'FF5733',
                                    'mid_color':'FFB233',
                                    'max_color': 'C7FF33',
                                    'min_value': 0,
                                    'max_vallue': 100})

writer.save()

在调整列宽大小和将数字格式应用于指定列方面,代码中的所有功能均正常运行,但是我无法获得要应用的条件格式。

我曾尝试在堆栈交换中搜索所有其他问题,但我找不到答案。

python excel pandas xlsxwriter
1个回答
0
投票

您在条件格式中有一些语法错误,例如未指定HTML格式的颜色和max_value的错字。修复这些问题后,它应该可以工作。这是一个基于您的较小的工作示例:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Apply a conditional format to the cell range.
worksheet.conditional_format('B2:B8', 
                             {'type': '3_color_scale',
                              'min_color': '#FF5733',
                              'mid_color': '#FFB233',
                              'max_color': '#C7FF33',
                              'min_value': 0,
                              'max_value': 100})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

© www.soinside.com 2019 - 2024. All rights reserved.