我无法更改 Pandas 库的 LaTeX 输出中的数字格式。
考虑这个例子:
import pandas as pd
values = [ { "id":"id1", "c1":1e-10, "c2":int(1000) }]
df = pd.DataFrame.from_dict(values).set_index("id")
print(df)
输出:
c1 c2
id
id1 1.000000e-10 1000
假设我想要
c1
格式化为两位小数,c2
作为整数:
s = df.style
s.clear()
s.format({ "c1":"{:.2f}", "c2":"{:d}" })
print(s.to_latex())
输出:
\begin{tabular}{lrr}
& c1 & c2 \\
id & & \\
id1 & 0.00 & 1000 \\
\end{tabular}
但是,我不需要
df
的 LaTeX 表格,而是 df.T
。
问题:因为我只能为列指定样式(至少在docs中看起来如此),如何为
df.T
指定基于行的输出格式?
如果我简单地写这个:
dft = df.T
s2 = dft.style
# s2.clear() # nothing changes with this instruction
print(s2.to_latex())
我得到的情况越来越糟:
\begin{tabular}{lr}
id & id1 \\
c1 & 0.000000 \\
c2 & 1000.000000 \\
\end{tabular}
甚至使用默认样式/格式,整数(值为
int(1000)
的整数)也变成了浮点数。
我使用了
subset
参数和各种切片,但没有成功。
作为解决方法,您可以使用以下方法将每个值格式化为正确的值:
fmt = { "c1":"{:.2f}", "c2":"{:d}" }
df_print = df.apply(lambda x: [fmt[x.name].format(v) for v in x])
print(df_print.T.style.to_latex())
输出:
\begin{tabular}{ll}
{id} & {id1} \\
c1 & 0.00 \\
c2 & 1000 \\
\end{tabular}