gsm*_*fra 6 python latex pandas
我想将一些DataFrame导出到LaTeX,但这些DataFrame有很多列,但没有那么多项.解决方案是显示转置的表格.我知道pandas的转置,但我想格式化我的行,方法to_latex只支持按列格式化.
一些代码:
import pandas as pd
names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]
tralala = [0.1, 0.2, 0.3, 0.4, 0.5]
BabyDataSet = zip(names,births,tralala)
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births', 'Whatever'])
df = df.transpose()
print df.to_latex()
Run Code Online (Sandbox Code Playgroud)
输出:
\begin{tabular}{llllll}
\toprule
{} & 0 & 1 & 2 & 3 & 4 \\
\midrule
Names & Bob & Jessica & Mary & John & Mel \\
Births & 968 & 155 & 77 & 578 & 973 \\
Whatever & 0.1 & 0.2 & 0.3 & 0.4 & 0.5 \\
\bottomrule
\end{tabular}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想这样做,例如:
\begin{tabular}{llllll}
\toprule
{} & 0 & 1 & 2 & 3 & 4 \\
\midrule
Names & Bob & Jessica & Mary & John & Mel \\
Births & 9.7e2 & 1.6e2 & 7.7e1 & 5.8e2 & 9.7e2 \\
Whatever & 0.1 & 0.2 & 0.3 & 0.4 & 0.5 \\
\bottomrule
\end{tabular}
Run Code Online (Sandbox Code Playgroud)
有没有办法破解这个功能?我唯一想到的是在转置和导出之前手动应用将我的所有列转换为字符串的格式
我想出了这个:
for key in df.columns.values:
if key in formatters:
df[key] = df[key].apply(formatters[key])
print df.to_latex()
Run Code Online (Sandbox Code Playgroud)
这几乎相当于
print df.to_latex(formatters=formatters)
Run Code Online (Sandbox Code Playgroud)
并且也可以使用转置的数据帧,即df.T.to_latex()