Skip to content

描述统计

计算均值、标准差、最值等常用描述统计量。

核心代码

py
    def _fit_descriptive(self, df: pd.DataFrame, decimals: int, title: str) -> None:
        """
        执行描述性统计分析
        
        参数:
            df: 清洗后的数据框
            decimals: 小数位数
            title: 表格标题
        """
        desc = df.describe().T
        
        # 列名映射
        col_map = {
            'count': 'N', 'mean': 'Mean', 'std': 'Std.Dev',
            'min': 'Min', 'max': 'Max', 'p50': 'Median'
        }
        
        # 构造最终表格
        final_cols = []
        rename_map = {}
        
        for opt in self.desc_options:
            # 将nobs映射为count
            if opt == 'nobs':
                opt = 'count'
            # Pandas describe 输出的百分位数键名是 '50%'
            pd_key = '50%' if opt == 'p50' else opt
            if pd_key in desc.columns:
                if pd_key not in final_cols:  # 避免重复添加
                    final_cols.append(pd_key)
                    rename_map[pd_key] = col_map.get(opt, opt)
        
        final_df = desc[final_cols].rename(columns=rename_map)
        
        # N 列转为整数
        if 'N' in final_df.columns:
            final_df['N'] = final_df['N'].astype(int)
        
        # 生成 HTML
        title = title if title else "Descriptive Statistics"
        self.custom_html = self._generate_html_table(final_df, title, decimals=decimals)

Released under the AGPL-3.0 License.