根据熊猫数据框范围设置单元格格式

时间:2019-05-21 23:05:05

标签: python-3.x pandas xlsxwriter

我有两个熊猫数据框,如下所示。我想将第二个数据框(df2)中所有行的字体颜色更改为红色(代码应采用数据框范围而不是A7:A8,因为该范围可能会根据数据框而增大或减小)

import pandas as pd

df1 = pd.DataFrame({'Data1': [10, 20, 30],
                   'Data2': [11, 21, 31],
                   'Date': [pd.to_datetime('today'), 
                            "", 
                            pd.to_datetime('today')]})
df2 = pd.DataFrame({'Data1': ["A", "B"]})

writer = pd.ExcelWriter('pandas_filter.xlsx', engine='xlsxwriter', )
workbook  = writer.book

df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=df1.shape[0]+2 , startcol=0)
writer.save()

我期望输出如下面的屏幕截图所示 enter image description here

以下代码似乎无效:

import pandas as pd

df1 = pd.DataFrame({'Data1': [10, 20, 30],
                   'Data2': [11, 21, 31],
                   'Date': [pd.to_datetime('today'), 
                            "", 
                            pd.to_datetime('today')]})
df2 = pd.DataFrame({'Data1': ["A", "B"]})

writer = pd.ExcelWriter('pandas_filter.xlsx', engine='xlsxwriter', )
workbook  = writer.book

df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=df1.shape[0]+2 , startcol=0)

def to_red():
    return 'color: red'

df2.style.applymap(to_red)

writer.save()

1 个答案:

答案 0 :(得分:1)

您需要在定义的函数中传递参数,并且必须将样式对象重新分配回df2。

尝试:

df1 = pd.DataFrame({'Data1': [10, 20, 30],
                   'Data2': [11, 21, 31],
                   'Date': [pd.to_datetime('today'), 
                            "", 
                            pd.to_datetime('today')]})
df2 = pd.DataFrame({'Data1': ["A", "B"]})

writer = pd.ExcelWriter('pandas_filter.xlsx', engine='xlsxwriter', )
workbook  = writer.book


#Note change in following line
def to_red(val):
    return 'color: red'

df2 = df2.style.applymap(to_red)
#Note move write lines after saving stying to df2 variable again.
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=df1.shape[0]+2 , startcol=0)

writer.save()

输出:

enter image description here