将dataframe添加到texttable里面,实现格式化输出。
data=[{"name":"Amay","age":20,"result":80}, {"name":"Tom","age":32,"result":90}]df=pd.DataFrame(data,columns=['name','age','result'])print(df)datafrma如下,现在要给其添加上表格框线。利用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表示不将第一参数的第一行作为标题,这样我们之前的添加的标题就会起作用了'''print(tb.draw())上面就是设置表格输出的对其格式,以及列的数据类型。‘set_cols_align是对水平位置上的左中右靠齐。‘l'表示向左。‘c'表示居中,'r'向右。
set_col_dtype用于设置列的数据类型、数据类型的对应如:
['t', # text'f', # float (decimal)'e', # float (exponent)'i', # integer'a' # automatic]tb.header(df.columns.get_values()) 这句是添加标题。 tb.add_rows(df.values,header=False) 这句是添加数据行。默认会将数据行的第一行作为标题。如果我们不设置header=False的话,返回结果:
之前指定的标题没起作用。应该是将第一行作为标题了。
设置了header=False后结果就出来了:
最后发一下完整的代码:
# -*- 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表示不将第一参数的第一行作为标题,这样我们之前的添加的标题就会起作用了'''print(tb.draw())以上这篇pandas dataframe添加表格框线输出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。