【问题标题】:coloring cell while exporting dataframe to excel将数据框导出到excel时为单元格着色
【发布时间】:2018-06-08 17:07:08
【问题描述】:

我有如下数据框“df”:

x = [1,3,5,7] 
y1 = [3,2,2,2] 
y2 = [2,5,2,2] 
y3 = [7,2,2,1]
df = pd.DataFrame({'x': x, 'y1': y1, 'y2': y2, 'y3': y3})

writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

我希望 excel 输出文件在 x 列与其他列的相互值中显示相同的颜色。 :

【问题讨论】:

    标签: pandas dataframe pandas.excelwriter


    【解决方案1】:

    如果颜色由dictionary指定,您可以使用styles:

    def color(a):
        d = {1:'yellow', 3:'green', 5:'blue', 7:'red'}
    
        d1 = {k: 'background-color:' + v for k, v in d.items()}
        df1 = pd.DataFrame(index=a.index, columns=a.columns)
        df1 = a.applymap(d1.get).fillna('')
        return df1
    
    df.style.apply(color, axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)
    

    【讨论】:

    • 谢谢,但它给出了这个错误:“AttributeError: 'Styler' object has no attribute 'to_excel'”
    • @P.J 你的熊猫版本是什么?
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多