pandas to_excel 添加顏色操作
我就廢話不多說了,大家還是直接看代碼吧~
import pandas as pd import numpy as np columns = [['A', 'A', 'B', 'B', 'C'], ['a', 'b', 'c', 'd', 'e']] # 創(chuàng)建形狀為(10,5) 的DataFrame 并設(shè)置二級標(biāo)題 demo_df = pd.DataFrame(np.arange(50).reshape(10, 5), columns=columns) print(demo_df) def style_color(df, colors): """ :param df: pd.DataFrame :param colors: 字典 內(nèi)容是 {標(biāo)題:顏色} :return: """ return df.style.apply(style_apply, colors=colors) def style_apply(series, colors, back_ground=''): """ :param series: 傳過來的數(shù)據(jù)是DataFramt中的一列 類型為pd.Series :param colors: 內(nèi)容是字典 其中key 為標(biāo)題名 value 為顏色 :param back_ground: 北京顏色 :return: """ series_name = series.name[0] a = list() # 為了給每一個單元格上色 for col in series: # 其中 col 為pd.DataFrame 中的 一個小單元格 大家可以根據(jù)不同需求為單元格設(shè)置不同的顏色 # 獲取什么一級標(biāo)題獲取什么顏色 if series_name in colors: for title_name in colors: if title_name == series_name: back_ground = 'background-color: ' + colors[title_name] # '; border-left-color: #080808' a.append(back_ground) return a style_df = style_color(demo_df, {"A": '#1C1C1C', "B": '#00EEEE', "C": '#1A1A1A'}) with pd.ExcelWriter('df_style.xlsx', engine='openpyxl') as writer: #注意: 二級標(biāo)題的to_excel index 不能為False style_df.to_excel(writer, sheet_name='sheet_name')
以上就是pandas.DataFrame 二級標(biāo)題to_excel() 添加顏色的demo 大家可以自行根據(jù)不同需求修改
主要注意
style_apply 方法中的內(nèi)容 里面是真正設(shè)置顏色的地方
補(bǔ)充知識:對pandas的dataframe自定義顏色顯示
原始表是這樣,一堆數(shù)字視覺表達(dá)能力很差
quantity_year.style.background_gradient(cmap='gray_r')
按照大小對其進(jìn)行不同顏色的填充,視覺表達(dá)能力強(qiáng)了很多。 也可以自定義顏色填充,比如我這里對大于平均值的進(jìn)行顏色填充。
quantity_year.style.applymap(lambda v : 'background-color: %s' %'#FFCCFF' if v>quantity_year.mean().mean() else'background-color: %s'% '')
當(dāng)然也可以自己def 更復(fù)雜的功能,都是大同小異。當(dāng)然還有highlight_max(‘color'),highlight_min(‘color')這種高亮最小最大值,也有hide_index()這種隱藏索引的小操作,在這里記錄一下。
以上這篇pandas to_excel 添加顏色操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解利用Python scipy.signal.filtfilt() 實現(xiàn)信號濾波
這篇文章主要介紹了詳解利用Python scipy.signal.filtfilt() 實現(xiàn)信號濾波,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06關(guān)于Python常用函數(shù)中NumPy的使用
這篇文章主要介紹了關(guān)于Python常用函數(shù)中NumPy的使用,在Python中有很多常用的函數(shù),NumPy就是其中之一,那么NumPy該怎么使用,下面就一起來看看吧2023-03-03淺談Python xlwings 讀取Excel文件的正確姿勢
這篇文章主要介紹了淺談Python xlwings 讀取Excel文件的正確姿勢,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02Python??reduce()函數(shù)的用法示例代碼
reduce函數(shù)原本在python2中也是個內(nèi)置函數(shù),不過在python3中被移到functools模塊中,這篇文章主要介紹了Python reduce()函數(shù)的用法,需要的朋友可以參考下2023-05-05