Skip to content

Commit

Permalink
Refactor multiindex unmerging to be cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
tomneep committed Mar 6, 2018
1 parent 5dbe1af commit d63e88f
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,37 +904,34 @@ def get_col_type(dtype):

# reestablish the MultiIndex that has been joined by _to_str_column
if self.fmt.index and isinstance(self.frame.index, MultiIndex):
out = self.frame.index.format(
adjoin=False, sparsify=self.fmt.sparsify,
names=any(self.frame.index.names), na_rep=self.fmt.na_rep
)

# index.format will sparsify repeated entries with empty strings
# so pad these with some empty space
def pad_empties(x):
for pad in x[::-1]:
if pad:
break
return [x[0]] + [i if i else ' ' * len(pad) for i in x[1:]]
out = (pad_empties(x) for x in out)

# Add empty spaces for each column level
clevels = self.frame.columns.nlevels
out = [[' ' * len(x[-1])] * clevels + x for x in out]

# Add the column names to the last index column
cnames = self.frame.columns.names
if any(cnames):
new_names = [i if i else '{}' for i in cnames]
out[self.frame.index.nlevels - 1][:clevels] = new_names

# Get rid of old multiindex column and add new ones
strcols.pop(0)
name = any(self.frame.index.names)
cname = any(self.frame.columns.names)
lastcol = self.frame.index.nlevels - 1
previous_lev3 = None
for i, lev in enumerate(self.frame.index.levels):
lev2 = lev.format()
blank = (' ' * len(lev2[0]) if lev2 else
' ' * len(self.fmt.na_rep))
# display column names in last index-column
if cname and i == lastcol:
lev3 = [x if x else '{}' for x in self.frame.columns.names]
else:
lev3 = [blank] * clevels
if name:
lev3.append(lev.name)
current_idx_val = None
for level_idx in self.frame.index.labels[i]:
idx_val = (lev2[level_idx] if level_idx >= 0 else
self.fmt.na_rep)
if ((previous_lev3 is None or
previous_lev3[len(lev3)].isspace()) and
idx_val == current_idx_val):
# same index as above row and left index was the same
lev3.append(blank)
else:
lev3.append(idx_val)
current_idx_val = idx_val
strcols.insert(i, lev3)
previous_lev3 = lev3
for i, o in enumerate(out):
strcols.insert(i, o)

column_format = self.column_format
if column_format is None:
Expand Down

0 comments on commit d63e88f

Please sign in to comment.