Python/Pandas中的描述性统计,括号中有std

2024-04-26 17:52:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题涉及在Python中进行描述性统计的最佳实践,其格式化输出对应于学术出版物中的表格:在下面的括号中有它们各自的标准偏差。最终目标是能够以Latex表格格式(或其他格式,html等)导出它。在

示例(Deucherta & Eugster (2018)):

enter image description here

熊猫:

对熊猫进行描述性统计的经典方法是使用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

我想要的是以下输出:

^{pr2}$

最好有一个能处理多索引数据帧的解决方案:

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:

第二个意思是,std没有找到解决方案。在

然后我想将我的df导出到latex:

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中有一些描述性的统计函数,但我在GitHub上读到,它们在某种程度上被弃用了。在

那么做这些桌子最好的方法是什么?在


Tags: 方法dfagenprandom解决方案meandesc