通过pandas xlsxwriter表循环

时间:2018-04-09 14:27:11

标签: python pandas xlsxwriter

我想使用pandas在excel表中创建一个条件格式。如果A列和B列小于C列中的相应值,则列A和B应为红色。如何正确完成,以及为什么我的循环会提前停止2行?

import numpy as np
import pandas as pd

d = pd.DataFrame(np.random.randint(1, 4, (15, 3)), columns = ['A', 'B', 'C'])

writer = pd.ExcelWriter('c:\\users\\MYNAME\\desktop\\xl_loop.xlsx') # please change!
d.to_excel(writer, 'Sheet1', index = False)
worksheet = writer.sheets['Sheet1']

for i in (range(d.shape[0])):
    worksheet.conditional_format(
        'A{}:B{}'.format(i, i),
        {'type': 'icon_set',
         'icon_style': '3_traffic_lights',
         'icons': [{'criteria': '>', 'type': 'number', 'value': d.iloc[i, 2]},
                    {'criteria': '=', 'type': 'number', 'value': d.iloc[i, 2]},
                    {'criteria': '<', 'type': 'number', 'value': d.iloc[i, 2]} ]} )
writer.save()

2 个答案:

答案 0 :(得分:3)

您可以使用Styling

(d.style
  .apply(lambda c: (c < d['C']).map({True:'background-color: red', False:''}))
  .to_excel('c:/temp/res.xlsx', index=False, engine='openpyxl'))

结果:

enter image description here

答案 1 :(得分:3)

您的范围计算和定位中存在一些逐个错误,这就是您的范围短2行的原因。

但是,没有必要为每一行创建条件格式。您可以按如下方式为整个范围创建一个:

import numpy as np
import pandas as pd

d = pd.DataFrame(np.random.randint(1, 4, (15, 3)), columns = ['A', 'B', 'C'])

writer = pd.ExcelWriter('xl_loop.xlsx')
d.to_excel(writer, 'Sheet1', index = False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

red_format = workbook.add_format({'bg_color': '#FFC7CE',
                                  'font_color': '#9C0006'})

start_row = 1
end_row   = start_row + d.shape[0] -1
start_col = 0
end_col   = 1

worksheet.conditional_format(start_row, start_col, end_row, end_col,
    {'type': 'cell',
     'criteria': '<',
     'value': '$C2',
     'format': red_format})

writer.save()

输出:

enter image description here