Skip to content

Commit a727a19

Browse files
committed
ENH: _to_str_columns accepts now optional header
Hereby also to_latex and to_string accept optional headers
1 parent 3f91d5a commit a727a19

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

pandas/formats/format.py

+26-8
Original file line numberDiff line numberDiff line change
@@ -489,30 +489,48 @@ def _to_str_columns(self):
489489
str_index = self._get_formatted_index(frame)
490490
str_columns = self._get_formatted_column_labels(frame)
491491

492-
if self.header:
492+
has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index))
493+
if not (has_aliases or self.header):
493494
stringified = []
494495
for i, c in enumerate(frame):
495-
cheader = str_columns[i]
496-
max_colwidth = max(self.col_space or 0, *(self.adj.len(x)
497-
for x in cheader))
498496
fmt_values = self._format_col(i)
499497
fmt_values = _make_fixed_width(fmt_values, self.justify,
500-
minimum=max_colwidth,
498+
minimum=(self.col_space or 0),
499+
adj=self.adj)
500+
stringified.append(fmt_values)
501+
elif has_aliases:
502+
if len(self.header) != len(self.columns):
503+
raise ValueError(('Writing %d cols but got %d aliases'
504+
% (len(self.columns), len(self.header))))
505+
stringified = []
506+
for i, c in enumerate(frame):
507+
cheader = [self.header[i]]
508+
header_colwidth = max(self.col_space or 0,
509+
*(self.adj.len(x) for x in cheader))
510+
fmt_values = self._format_col(i)
511+
fmt_values = _make_fixed_width(fmt_values, self.justify,
512+
minimum=header_colwidth,
501513
adj=self.adj)
502514

503515
max_len = max(np.max([self.adj.len(x) for x in fmt_values]),
504-
max_colwidth)
516+
header_colwidth)
505517
cheader = self.adj.justify(cheader, max_len, mode=self.justify)
506518
stringified.append(cheader + fmt_values)
507519
else:
508520
stringified = []
509521
for i, c in enumerate(frame):
522+
cheader = str_columns[i]
523+
header_colwidth = max(self.col_space or 0,
524+
*(self.adj.len(x) for x in cheader))
510525
fmt_values = self._format_col(i)
511526
fmt_values = _make_fixed_width(fmt_values, self.justify,
512-
minimum=(self.col_space or 0),
527+
minimum=header_colwidth,
513528
adj=self.adj)
514529

515-
stringified.append(fmt_values)
530+
max_len = max(np.max([self.adj.len(x) for x in fmt_values]),
531+
header_colwidth)
532+
cheader = self.adj.justify(cheader, max_len, mode=self.justify)
533+
stringified.append(cheader + fmt_values)
516534

517535
strcols = stringified
518536
if self.index:

0 commit comments

Comments
 (0)