这个问题涉及在Python中进行描述性统计的最佳实践,它的格式化输出与学术出版物中的表相对应:在下面的括号中分别包含其标准偏差的平均值。最终目标是能够以乳胶表格格式(或其他格式、html等)导出它。
熊猫:
在熊猫身上做描述性统计的经典方法是使用
describe()
方法
DataFrame
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)
我没有找到隐藏第二个索引列(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表似乎是最有前途的解决方案。但我不知道如何实现它。StatsModels中有一些描述性的stats函数,但我在GitHub上看到,它们在某种程度上已被弃用。
那么做这些桌子的最好方法是什么?