30
30
sparsify : bool, optional
31
31
Set to False for a DataFrame with a hierarchical index to print every
32
32
multiindex key at each row, default True
33
+ justify : {'left', 'right'}, default 'left'
34
+ Left or right-justify the column labels
33
35
index_names : bool, optional
34
36
Prints the names of the indexes, default True """
35
37
@@ -46,7 +48,8 @@ class DataFrameFormatter(object):
46
48
47
49
def __init__ (self , frame , buf = None , columns = None , col_space = None ,
48
50
header = True , index = True , na_rep = 'NaN' , formatters = None ,
49
- float_format = None , sparsify = True , index_names = True ):
51
+ justify = 'left' , float_format = None , sparsify = True ,
52
+ index_names = True ):
50
53
self .frame = frame
51
54
self .buf = buf if buf is not None else StringIO ()
52
55
self .show_index_names = index_names
@@ -57,6 +60,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
57
60
self .col_space = col_space
58
61
self .header = header
59
62
self .index = index
63
+ self .justify = justify
60
64
61
65
if columns is not None :
62
66
self .columns = _ensure_index (columns )
@@ -81,11 +85,21 @@ def to_string(self):
81
85
str_index = self ._get_formatted_index ()
82
86
str_columns = self ._get_formatted_column_labels ()
83
87
84
- if self .header :
85
- stringified = [str_columns [i ] + self ._format_col (c )
86
- for i , c in enumerate (self .columns )]
87
- else :
88
- stringified = [self ._format_col (c ) for c in self .columns ]
88
+ stringified = []
89
+
90
+ for i , c in enumerate (self .columns ):
91
+ if self .header :
92
+ fmt_values = self ._format_col (c )
93
+ cheader = str_columns [i ]
94
+ max_len = max (max (len (x ) for x in fmt_values ),
95
+ max (len (x ) for x in cheader ))
96
+ if self .justify == 'left' :
97
+ cheader = [x .ljust (max_len ) for x in cheader ]
98
+ else :
99
+ cheader = [x .rjust (max_len ) for x in cheader ]
100
+ stringified .append (cheader + fmt_values )
101
+ else :
102
+ stringified = [self ._format_col (c ) for c in self .columns ]
89
103
90
104
if self .index :
91
105
to_write .append (adjoin (1 , str_index , * stringified ))
0 commit comments