Closed
Description
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}
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}
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}
Albeit this might be quite difficult to code and have other repercussions.