將dataframe添加到texttable里面,實(shí)現(xiàn)格式化輸出。
data=[{"name":"Amay","age":20,"result":80}, {"name":"Tom","age":32,"result":90}]df=pd.DataFrame(data,columns=['name','age','result'])print(df)datafrma如下,現(xiàn)在要給其添加上表格框線。利用texttable。

tb=Texttable()tb.set_cols_align(['l','r','r'])tb.set_cols_dtype(['t','i','i'])tb.header(df.columns.get_values())tb.add_rows(df.values,header=False)'''header=False表示不將第一參數(shù)的第一行作為標(biāo)題,這樣我們之前的添加的標(biāo)題就會(huì)起作用了'''print(tb.draw())
上面就是設(shè)置表格輸出的對(duì)其格式,以及列的數(shù)據(jù)類型。‘set_cols_align是對(duì)水平位置上的左中右靠齊。‘l'表示向左。‘c'表示居中,'r'向右。
set_col_dtype用于設(shè)置列的數(shù)據(jù)類型、數(shù)據(jù)類型的對(duì)應(yīng)如:
['t', # text'f', # float (decimal)'e', # float (exponent)'i', # integer'a' # automatic]
tb.header(df.columns.get_values()) 這句是添加標(biāo)題。 tb.add_rows(df.values,header=False) 這句是添加數(shù)據(jù)行。默認(rèn)會(huì)將數(shù)據(jù)行的第一行作為標(biāo)題。如果我們不設(shè)置header=False的話,返回結(jié)果:

之前指定的標(biāo)題沒起作用。應(yīng)該是將第一行作為標(biāo)題了。
設(shè)置了header=False后結(jié)果就出來了:

最后發(fā)一下完整的代碼:
# -*- coding: utf-8 -*-"""Created on Tue Jan 8 16:47:17 2019Python Version:3.6.7@author: Fanxiaolei"""import pandas as pdfrom texttable import Texttabledata=[{"name":"Amay","age":20,"result":80}, {"name":"Tom","age":32,"result":90}]df=pd.DataFrame(data,columns=['name','age','result'])print(df)print('添加表格線之后:')tb=Texttable()tb.set_cols_align(['l','r','r'])tb.set_cols_dtype(['t','i','i'])tb.header(df.columns.get_values())tb.add_rows(df.values,header=False)'''header=False表示不將第一參數(shù)的第一行作為標(biāo)題,這樣我們之前的添加的標(biāo)題就會(huì)起作用了'''print(tb.draw())以上這篇pandas dataframe添加表格框線輸出的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林站長(zhǎng)站。
|
新聞熱點(diǎn)
疑難解答
圖片精選