Python:Pandas样式背景颜色在excel文件中不可见

时间:2019-05-25 12:01:24

标签: python excel pandas dataframe

我正在使用xlsxwriter作为引擎来创建具有多个工作表的excel文件。

在每个工作表中,行颜色基于名为colour的列的值

但是颜色在我的excel文件中不可见。

import pandas as pd

def row_colour(row):
    return ['background-color:'+row.colour.lower()for i in row]


writer = pd.ExcelWriter('try.xlsx', engine='xlsxwriter')

cols = ['subject','colour']
df1 = pd.DataFrame([['Math','DarkRed'],['Science','Yellow']],columns=cols)

df2 = pd.DataFrame([['English','Orange'],['History','Green']],columns=cols)

df3 = pd.DataFrame([['Geography','DarkRed'],['Civic','Yellow']],columns=cols)

df1.style.apply(row_colour,axis=1)
df2.style.apply(row_colour,axis=1)
df3.style.apply(row_colour,axis=1)

df1.to_excel(writer, sheet_name='Sheet 1')
df2.to_excel(writer, sheet_name='Sheet 2')
df3.to_excel(writer, sheet_name='Sheet 3')

writer.save()

在输出中看不到颜色:

enter image description here

接受的答案是上述问题的正确答案。

我通过删除颜色列改进了任务,因为它仅用于为行着色。

代码:

import pandas as pd

def row_colour(table,color):
    print("table: \n "+str(table))
    print("table shape : "+str(table.shape))
    color_data = []

    for index,row in table.iterrows():
        color.iloc[index]
        if str(color.iloc[index]['colour']) == "DarkRed":
            c= 'background-color:red'
        else:
            c= 'background-color:'+str(color.iloc[index]['colour'])
        color_data.append([c for i in range(len(row))])


    return pd.DataFrame(color_data,index=table.index, columns=table.columns)


writer = pd.ExcelWriter('try.xlsx', engine='xlsxwriter')

cols = ['subject','colour']
df1 = pd.DataFrame([['Math','DarkRed'],['Science','Yellow']],columns=cols)

df2 = pd.DataFrame([['English','Orange'],['History','Green']],columns=cols)

df3 = pd.DataFrame([['Geography','DarkRed'],['Civic','Yellow']],columns=cols)

color = pd.DataFrame(columns=['colour'])
color['colour']=df1['colour']
df1 = df1.drop(['colour'],axis=1)
df1=df1.style.apply(row_colour,axis=None,color=color)

color = pd.DataFrame(columns=['colour'])
color['colour']=df2['colour']
df2=df2.drop(['colour'],axis=1)
df2=df2.style.apply(row_colour,axis=None,color=color)

color = pd.DataFrame(columns=['colour'])
color['colour']=df3['colour']
df3=df3.drop(['colour'],axis=1)
df3=df3.style.apply(row_colour,axis=None,color=color)

df1.to_excel(writer, sheet_name='Sheet 1')
df2.to_excel(writer, sheet_name='Sheet 2')
df3.to_excel(writer, sheet_name='Sheet 3')

writer.save()


2 个答案:

答案 0 :(得分:1)

该功能还可以,您只需重新分配df1,df2,df3。这应该起作用:

import pandas as pd

def row_colour(row):
    return ['background-color:'+row.colour.lower()for i in row]


writer = pd.ExcelWriter('try.xlsx', engine='xlsxwriter')

cols = ['subject','colour']
df1 = pd.DataFrame([['Math','DarkRed'],['Science','Yellow']],columns=cols)
df2 = pd.DataFrame([['English','Orange'],['History','Green']],columns=cols)
df3 = pd.DataFrame([['Geography','DarkRed'],['Civic','Yellow']],columns=cols)

df1 = df1.style.apply(row_colour,axis=1)
df2 = df2.style.apply(row_colour,axis=1)
df3 = df3.style.apply(row_colour,axis=1)

df1.to_excel(writer, sheet_name='Sheet 1')
df2.to_excel(writer, sheet_name='Sheet 2')
df3.to_excel(writer, sheet_name='Sheet 3')

writer.save()

to_excel此处是pandas.io.formats.style.Styler的一种方法,而不是原始数据框。

答案 1 :(得分:0)

作为对您的评论的答复,我想出了一个更复杂的解决方案。 现在,在删除颜色之前,可以从DataFrame中读取颜色。然后作为参数传递给行着色函数。 关键是我使用zip和pd.IndexSlice子集df.style.apply。我希望这能满足您的着色需求。

const card = document.querySelector('.card');
const cards = document.querySelectorAll('.card')
const taskContainers = document.querySelectorAll('.taskContainer');

// card listeners
card.addEventListener('dragstart', dragStart);
card.addEventListener('dragend', dragEnd);

// Loop through taskContainer boxes and add listeners
for (const taskContainer of taskContainers) {
    taskContainer.addEventListener('dragover', dragOver);
    taskContainer.addEventListener('dragenter', dragEnter);
    taskContainer.addEventListener('dragleave', dragLeave);
    taskContainer.addEventListener('drop', dragDrop);
}

// Drag Functions
function dragStart() {
    this.className += ' hold';
    setTimeout(() => (this.className = 'invisible'), 0); //set timeout so card wont dissapear
}

function dragEnd() {
    this.className = 'card';
}

function dragOver(e) {
    e.preventDefault();
}

function dragEnter(e) {
    e.preventDefault();
    this.className += ' hover';
}

function dragLeave() {
    this.className = 'taskContainer';
}

function dragDrop() {
    this.className = 'taskContainer';
    this.append(card);
}

//add card function
function addTaskContainer() {
    var taskContainer = document.createElement('div');
    taskContainer.className = "taskContainer";
    taskContainer.id = "add-new-card";
    document.getElementById("backlog").append(taskContainer);
}

function addCard() {
    addTaskContainer();
    var card = document.createElement('div');
    card.className = "card";
    card.id = "new-card";
    document.getElementById("add-new-card").appendChild(card);
    document.getElementById("new-card").setAttribute('draggable', true);
}