Я хотел бы иметь возможность контролировать цвет фона ячейки в Excel. У меня большие объемы данных, и мне нужно определить, соответствуют ли данные ожиданиям или нет. Это я могу сделать уже с Python. Тем не менее, я хотел бы отобразить эти данные в Excel, и, чтобы их было легче читать, я хотел бы раскрасить ячейки в зависимости от того, хороши данные или нет.
Я уже использовал style.applymap
, чтобы назначить цвет ячейке на основе определенных значений ячейки. Например, если в ячейке написано «ошибка», я могу покрасить ее в красный цвет.
Так что, если я пройдусь по данным и создам новый список «пройти» / «потерпеть неудачу» и введу эти значения в документ Excel, я смогу получить то, что хочу, с точки зрения цвета. Этот код показан ниже, и я могу получить что-то похожее на это ![The Pass/Fail column has 'pass' or 'fail' as text, and this is used to define the cell colour](https://i.stack.imgur.com/8WmgZ.png)
Однако, если я хочу ввести фактические значения в ячейки, то я понятия не имею, как получить требуемые цвета фона.
Что у меня так далеко:
import pandas as pd
#in the example, I have a list of office items, chairs and computers
names=['chair1','chair2','chair3','chair4','chair5','computer1','computer2','computer3','computer4','computer5']
#Each name has an assigned type. The type determines what the expectations are for the lifetime
inv_type=['furniture','furniture','furniture','furniture','furniture','electronics','electronics','electronics','electronics','electronics']
#The age of each item before breakdown is recorded here
inv_age=[2.2, 5, 7.3, 0.6, 4.3, 3.2, 1.7, 2.3, 2.2 ,0.9]
# a dictionary defines the minimum expected lifetime
expected_life={'furniture':4,'electronics':2}
# initialise the pass_fail list
inventory_pass_fail=[]
# cyle through the items and append 'pass' or 'fail' to the list depending on if the item
#has reached the minimum expected age.
for i in range(len(names)):
if inv_age[i]>expected_life[inv_type[i]]:
inventory_pass_fail.append('pass')
else:
inventory_pass_fail.append('fail')
#get names, type, and pass/fail list into one list for the excel sheet
final_list_report=list(zip(*[names,inv_type,inventory_pass_fail]))
df = pd.DataFrame(final_list_report,columns=['Name','Type','Pass/Fail'])
#define function that determines background colour
def color_code_by_text(val):
if val=='N/A' or val=='pass':
color='background-color: %s' % 'green'
elif val=='fail':
color='background-color: %s' % 'red'
else:
color=''
return color
#use style.applymap and the color_code_by_text function to colour background cells
styled = (df.style.applymap(color_code_by_text))
# and save the end result
styled.to_excel('inventory_report.xlsx', engine='openpyxl')
Я попытался перезаписать тот же файл фактическими значениями. Это работает, но это также избавляет от цвета. То, что я хотел бы, это что-то вроде этого, где цвет указывает на состояние прохождения / неудачи, но ячейка содержит фактическое число:
![The Pass/Fail column has the actual values, but the colour indicates whether it has passed or failed.](https://i.stack.imgur.com/KzXVn.png)
Буду признателен за любые советы, спасибо!