本文介紹使用Pandas導(dǎo)出Excel终息,并添加一些簡單的格式
1 dataframe.to_excel導(dǎo)出Excel
df.to_excel(self,
excel_writer, # 輸出路徑
sheet_name='Sheet1', # 命名excel工作表名
na_rep='', # 缺失值填充 未檩,可以設(shè)置為字符串,數(shù)字,字符串;使用bool則用0和1代替
float_format=None, #數(shù)值類型的格式設(shè)置,'%.2f'保留2位有效數(shù)字
columns=None, # 選擇輸出的列弥咪,默認(rèn)所有列。
header=True, # 是否將第一行作為表頭十绑,也可以傳入list修改表頭
index=True, #是否輸出index 默認(rèn)為True聚至,也可以傳入int使用行號的值作為表頭
index_label=None, # 設(shè)置索引列的列名
startrow=0, #開始的行
startcol=0, #開始的列
engine=None, #輸出引擎,openpyxl”或“ xlsxwriter
merge_cells=True, #將MultiIndex和Hierarchical Rows寫入合并的單元格
encoding=None, #編碼孽惰,xlwt才需要
inf_rep='inf', #無窮大的值用什么表示
verbose=True, #明細(xì)日志
freeze_panes=None) #是否凍結(jié),傳入(row,col)
在一個excel中寫入多個sheet頁鸥印,必須使用ExcelWriter:
with pd.ExcelWriter('output.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet_name_1')
df2.to_excel(writer, sheet_name='Sheet_name_2')
2 使用pandas.io.format.style.Styler設(shè)置格式
使用DataFrame的style來配置單元格
2.1 隱藏索引
df.hide_index()
2.2 格式
Styler.format(self, formatter, subset=None, na_rep: Union[str, NoneType] = None)
formatter:表示需要轉(zhuǎn)換的格式
subset:需要作用的列勋功,默認(rèn)為所有列,傳入list
na_rep:替換缺失值库说,默認(rèn)不替換
示例:
df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
df['c'] = ['a', 'b', 'c', 'd']
#保留2位有效數(shù)字狂鞋,并使用百分比形式
# df.style.format("{:.2%}",subset=['a'])
#整數(shù)保留3位,小數(shù)保留2位
# df.style.format( '${3:,.2f}',subset=['b'])
#字符轉(zhuǎn)大些
df.style.format("{:.2%}",subset=['c'])
也可以用dic來傳入列及其對應(yīng)的轉(zhuǎn)換方式潜的,實現(xiàn)同時對多個列操作
df.style.format({'c':str.upper,'a':"{:.2%}"})
2.3 單元格背景色
一般來說骚揍,設(shè)置背景色無疑是根據(jù)值的大小來判斷而配色;或是直接將某列配色
2.3.1 使用applymap對每個元素配色
根據(jù)v值的情況來判斷其配色
'background-color: green'表示綠色啰挪;'background-color: '表示無背景色信不;也可以使用16進(jìn)制色號比如#BFE9C4。
data.style.applymap(lambda v: 'background-color: %s' % 'green' if v=='pm' else '' ,subset=['a'])
如果只想對某些列的某些行做操作亡呵,subset可以些為如下格式:
subset=pd.IndexSlice[2:5, ['B', 'D']]
2.3.2 使用apply對每一列配色
例子中傳入的x表示一列抽活,也就是一個series。
#判斷v是不是一列x的最大的值
def highlight_max(x):
return ['background-color: yellow' if v == x.max() else ''
for v in x]
df.style.apply(highlight_max)
2.4 快捷配色標(biāo)記
除了2.3中介紹的自定義的配色方法锰什,styles模塊也提供了幾個針對特定值的快捷方法下硕。
2.4.1 最大丁逝、最小值標(biāo)記
有如下幾個方法:
subset表示作用于哪些列;color表示顏色梭姓;axis=0表示列霜幼,=1表示1
#最大值
highlight_max(self, subset=None, color='yellow', axis=0)
#最小值
highlight_min(self, subset=None, color='yellow', axis=0)
示例:
df.highlight_max(color='lightgreen').highlight_min(color='red')
2.4.2 空值標(biāo)記
#空值,空值是針對所有元素來使用的誉尖,無法設(shè)置行列
highlight_null(self, color='red')
2.4.2 漸變色標(biāo)記
還有一個特殊的罪既,根據(jù)某些值的大小關(guān)系為其添加漸變色背景
background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, subset=None, text_color_threshold=0.408, vmin: Union[float, NoneType] = None, vmax: Union[float, NoneType] = None)
cmap表示漸變色系,其他色系可以參考這里释牺;
#示例
df.style.background_gradient(subset=['b'], cmap='BuGn')
2.4.3 選擇器顏色標(biāo)記[無法應(yīng)用于Excel]
可以指定當(dāng)鼠標(biāo)選中時候的顏色顯示
df.style.set_table_styles([{'selector': 'tr:hover','props': [('background-color', 'green')]}])
2.4.4 為其他無格式數(shù)據(jù)添加格式
#字體設(shè)置為敗訴萝衩,對其方式為右對齊
df.style.set_properties(color="white", align="right")
#背景顏色為黃色
df.style.set_properties(**{'background-color': 'yellow'})
2.5 迷你條形圖[無法應(yīng)用于Excel]
使用的是style的bar函數(shù)
Styler.bar(self, subset=None, axis=0, color='#d65f5f', width=100, align='left', vmin=None, vmax=None)
# align表示對齊方式,可以為left没咙,mid猩谊,zero
# vmin表示基準(zhǔn)值
2.6 其他
設(shè)置標(biāo)題
df.style.`set_cation('title')
清理格式
df.style.clear
空值替換
df.style.set_na_rep('defualt')
隱藏某些列
df.style.hide_columns(['a','b'])
2.8 單元格樣式
單元格樣式包含很多,其實background-color就屬于祭刚,其實我們可以使用apply或者applymap統(tǒng)一設(shè)置牌捷,方法可以看上文,這里不再贅述涡驮。內(nèi)容分隔如下:
'background-color:green;color:red'
2.8.1 color 字體顏色
2.8.2 border-style:邊框格式
none 定義無邊框暗甥。
hidden 與 "none" 相同。不過應(yīng)用于表時除外捉捅,對于表撤防,hidden 用于解決邊框沖突。
dotted 定義點狀邊框棒口。在大多數(shù)瀏覽器中呈現(xiàn)為實線寄月。
dashed 定義虛線。在大多數(shù)瀏覽器中呈現(xiàn)為實線无牵。
solid 定義實線漾肮。
double 定義雙線。雙線的寬度等于 border-width 的值茎毁。
2.8.3 border-width:邊框?qū)挾?/h4>
默認(rèn)3px克懊,設(shè)置為1px,導(dǎo)出excel是正常的框線七蜘。
2.8.4 border-color:邊框顏色
默認(rèn)black
2.8.5 text-align:文本水平對齊方式
left\right\center
2.8.6 font-style:字體樣式
normal 默認(rèn)值谭溉。瀏覽器顯示一個標(biāo)準(zhǔn)的字體樣式。
italic 瀏覽器會顯示一個斜體的字體樣式橡卤。
oblique 瀏覽器會顯示一個傾斜的字體樣式夜只。
2.8.7 font-family:字體
2.9 導(dǎo)出為html
df.style.render