Pandas Styler - MultiIndex 名称的自定义格式化程序

问题描述 投票:0回答:1

我一直在尝试使用样式器格式化 pandas 数据框。使用 MultiIndex 时,

format_index()
的行为似乎有点不可预测,而且我无法找到格式化 MultiIndex 名称的方法。

以下是带有极其愚蠢的格式化程序的MWE:

import pandas as pd
import numpy as np

data = {
    'Index1': ['A', 'B', 'C'],
    'Index2': ['X', 'Y', 'Z'],
    'Index3': ['1', '2', '3'],
    'Value1': np.random.randint(1, 100, 3),
    'Value2': np.random.randint(1, 100, 3),
    'Value3': np.random.randint(1, 100, 3)
}
df = pd.DataFrame(data)
df.set_index(['Index1', 'Index2', 'Index3'], inplace=True)

def custom_formatter(value):
    return 'S' + str(value)

styled_df = df.rename_axis(index=custom_formatter, columns=custom_formatter).style
styled_df = styled_df.format(custom_formatter).format_index(custom_formatter, axis=1).format_index(custom_formatter, axis = 0)
latex_table = styled_df.to_latex()
print(latex_table)

这会导致

\begin{tabular}{lllrrr}
\toprule
 &  & SNone & SValue1 & SValue2 & SValue3 \\
SIndex1 & SIndex2 & SIndex3 &  &  &  \\
\midrule
SA & SX & S1 & S62 & S81 & S52 \\
SB & SY & S2 & S15 & S24 & S25 \\
SC & SZ & S3 & S22 & S36 & S48 \\
\bottomrule
\end{tabular}

这几乎是我想要的(即格式化程序用于所有表格元素),但是

SNone
实际上应该为空 - 那里没有定义值。如果我删除
.rename_axis(...)
部分,它就是空白的。

有人对如何正确格式化 MultiIndex 或如何消除此错误有任何其他想法吗?我拥有索引的主要目标是将公共值分组为乳胶中的多行,如果有方法可以在没有索引的情况下实现这一目标,我也愿意接受建议。

python pandas dataframe multi-index styler
1个回答
0
投票

那是因为

df.columns.name
None
,当您将其转换为
str
时,您会得到一个文字
"None"

你可以这样修复它:

def custom_formatter(value):
    return f"S{value}" if value else ""

输出:

>>> print(styled_df.to_latex())

\begin{table}
\.index_name.level0:nth-of-type(3)lightgreen
\begin{tabular}{lllrrr}
 &  &  & SValue1 & SValue2 & SValue3 \\
SIndex1 & SIndex2 & SIndex3 &  &  &  \\
SA & SX & S1 & S45 & S68 & S84 \\
SB & SY & S2 & S48 & S68 & S22 \\
SC & SZ & S3 & S65 & S10 & S37 \\
\end{tabular}
\end{table}

© www.soinside.com 2019 - 2024. All rights reserved.