【发布时间】:2019-06-25 05:53:27
【问题描述】:
此问题涉及在 Python 中使用与学术出版物中的表格相对应的格式化输出进行描述性统计的最佳实践:表示其各自的标准偏差在下面的括号中。最终目标是能够以 Latex 表格格式(或其他格式、html 等)导出它。
示例 (Deucherta & Eugster (2018)):
熊猫:
在 Pandas 中进行描述性统计的经典解决方案是使用 DataFrame 的 describe() 方法。
import numpy as np
import pandas as pd
# Generate a DataFrame to have an example
df = pd.DataFrame(
{"Age" : np.random.normal(20,15,5),
"Income": np.random.pareto(1,5)*20_000 }
)
# The describe method to get means and stds
df.describe().loc[["mean", "std"]].T
>>>
mean std
Age 15.322797 13.449727
Income 97755.733510 143683.686484
我想要的是以下输出:
Age 15.32
(13.44)
Income 97755.73
(143683.68)
如果有一个适用于多索引数据框的解决方案会很好:
df2 = pd.DataFrame(
{"Age" : np.random.normal(20,15,5),
"Income": np.random.pareto(1,5)*20_000 }
)
df_c = pd.concat([df,df2], keys = ["A", "B"])
>>>
得到
A B
Age 23.15 21.33
(11.62) (9.34)
Income 68415.53 46619.51
(95612.40) (64596.10)
我目前的解决方案:
idx = pd.IndexSlice
df_desc = (df_c
).groupby(level = 0, axis = 0).describe()
df_desc = df_desc.loc[idx[:],idx[:,["mean", "std"]]].T
df_desc.loc[idx[:,["std"]],idx[:]] = df_desc.loc[idx[:,["std"]],idx[:]
].applymap(
lambda x: "("+"{:.2f}".format(x)+")")
print(df_desc)
>>>
A B
Age mean 23.1565 21.3359
std (11.62) (9.34)
Income mean 68415.5 46619.5
std (95612.40) (64596.10)
问题1:
我没有找到隐藏第二个索引列 [mean, std, mean,std] 的解决方案。
然后我想将我的 df 导出到乳胶:
df_desc.to_latex()
>>>
\begin{tabular}{llll}
\toprule
& & A & B \\
\midrule
Age & mean & 5.5905 & 29.5894 \\
& std & (16.41) & (13.03) \\
Income & mean & 531970 & 72653.7 \\
& std & (875272.44) & (79690.18) \\
\bottomrule
\end{tabular}
问题2:
表格的 & 字符未对齐,这使得编辑有点乏味(我在 VSCode 中使用扩展来对齐 &)
总的来说,我觉得这个解决方案乏味且不优雅。
解决方案?
如果没有复杂的字符串操作,我不知道我应该怎么做才能获得所需的结果。
我看过Pandas styling,但我不认为这是最好的解决方案。
还有StatModels Tables,但是我没有找到简单的解决我的问题的方法。 Statsmodels Tables 似乎是最有希望的解决方案。但我不知道如何实现它。 StatsModels 中有一些描述性的统计函数,但我在 GitHub 上读到它们在某种程度上已被弃用。
那么制作这些表格的最佳方法是什么?
【问题讨论】:
标签: python pandas statistics statsmodels standard-deviation