Skip to content

BUG: apply_index styles not universally applied across LaTeX multirows #41994

Closed
@attack68

Description

@attack68

PR #41993 makes Styler.applymap_index and Styler.apply_index compatible with to_latex. But, with MultiIndexes this introduces a bug: cell coloring is not universal for multirow, albeit multicols are OK.

df = pd.DataFrame({"A": [0, 1, 2], "B": [-0.61, -1.22, -2.22], "C": ["ab", "cd", "de"]})
cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
df.index, df.columns = ridx, cidx
styler = df.style
func = lambda v: 'cellcolor:{red}; color:{white}; bfseries:--rwrap;' if "A" in v or "Z" in v or "c" in v else None
print(styler.applymap_header(func, axis="columns").applymap_header(func).to_latex(hrules=True))
\begin{tabular}{llrrl}
\toprule
{} & {} & \multicolumn{2}{r}{\cellcolor{red} \color{white} \bfseries{Z}} & {Y} \\
{} & {} & {a} & {b} & {\cellcolor{red} \color{white} \bfseries{c}} \\
\midrule
\multirow[c]{2}{*}{\cellcolor{red} \color{white} \bfseries{A}} & a & 0 & -0.610000 & ab \\
 & b & 1 & -1.220000 & cd \\
B & \cellcolor{red} \color{white} \bfseries{c} & 2 & -2.220000 & de \\
\bottomrule
\end{tabular}

Screen Shot 2021-06-14 at 09 37 21

Even if the code is amended to print the styles in problem cells, albeit with a blank display value the problem is not solved because the text is overwritten:

\begin{tabular}{llrrl}
\toprule
{} & {} & \multicolumn{2}{r}{\cellcolor{red} \color{white} \bfseries{Z}} & {Y} \\
{} & {} & {a} & {b} & {\cellcolor{red} \color{white} \bfseries{c}} \\
\midrule
\multirow[c]{2}{*}{\cellcolor{red} \color{white} \bfseries{A}} & a & 0 & -0.610000 & ab \\
\cellcolor{red} \color{white} \bfseries{} & b & 1 & -1.220000 & cd \\
B & \cellcolor{red} \color{white} \bfseries{c} & 2 & -2.220000 & de \\
\bottomrule
\end{tabular}

Screen Shot 2021-06-14 at 09 39 03

One solution is to apply the multirow last so that it overwrites previous rendered cells, using a negative rowspan.

\begin{tabular}{llrrl}
\toprule
{} & {} & \multicolumn{2}{r}{\cellcolor{red} \color{white} \bfseries{Z}} & {Y} \\
{} & {} & {a} & {b} & {\cellcolor{red} \color{white} \bfseries{c}} \\
\midrule
\cellcolor{red} \color{white} \bfseries{} & a & 0 & -0.610000 & ab \\
\multirow[c]{-2}{*}{\cellcolor{red} \color{white} \bfseries{A}} & b & 1 & -1.220000 & cd \\
B & \cellcolor{red} \color{white} \bfseries{c} & 2 & -2.220000 & de \\
\bottomrule
\end{tabular}

Screen Shot 2021-06-14 at 09 41 13

Albeit this might be quite difficult to code and have other repercussions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closing CandidateMay be closeable, needs more eyeballsIO LaTeXto_latexStylerconditional formatting using DataFrame.style

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions