Skip to content

频数统计

统计变量各取值的频数与占比。

核心代码

py
    def _fit_frequency_single(self, var: str, decimals: int, title: str) -> None:
        """
        生成单变量频数统计表
        
        参数:
            var: 变量名
            decimals: 小数位数
            title: 表格标题
        """
        # 获取变量数据(删除缺失值)
        data_series = self.data[var].dropna()
        
        if len(data_series) == 0:
            raise ValueError(_('变量 %(var)s 没有有效数据。') % {'var': var})
        
        # 计算频数
        freq_counts = data_series.value_counts().sort_index()
        total = len(data_series)
        
        # 构建频数表
        freq_data = []
        cumulative_freq = 0
        cumulative_pct = 0.0
        
        for value, count in freq_counts.items():
            freq = int(count)
            percent = (count / total) * 100
            cumulative_freq += freq
            cumulative_pct += percent
            
            freq_data.append({
                'Value': str(value),
                'Freq.': freq,
                'Percent': f"{percent:.{decimals}f}",
                'Cum.': f"{cumulative_pct:.{decimals}f}"
            })
        
        # 添加总计行
        freq_data.append({
            'Value': 'Total',
            'Freq.': total,
            'Percent': f"{100.0:.{decimals}f}",
            'Cum.': f"{100.0:.{decimals}f}"
        })
        
        freq_df = pd.DataFrame(freq_data)
        title = title if title else f"Frequency Table: {var}"
        
        # 生成HTML(使用自定义样式,Total行加粗边框)
        self.custom_html = self._generate_frequency_html(freq_df, title, var)

Released under the AGPL-3.0 License.