You need to enable JavaScript to run this app. 如何计算Pandas DataFrame指定列频率占比并过滤NaN值
优惠活动
大模型
产品
解决方案
定价
更多

如何计算Pandas DataFrame指定列频率占比并过滤NaN值

问题需求

计算Pandas DataFrame中,A列分组下B列取值为'1'的样本数占总样本量的百分比,最终结果过滤掉空值。

完整可运行代码

首先修正示例代码中的笔误(A列多余的未加引号的bat元素),实现需求的代码如下:

import pandas as pd
df = pd.DataFrame({ 
    'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar', 'foo', 'bar'],
    'B': ['0', '0', '1', '1', '1', '0', '1', '0', '0', '0', '0'] 
})

# 统计总样本量
total_cnt = len(df)
# 筛选B='1'的记录按A分组,计算占比后格式化
res = df[df['B'] == '1'].groupby('A').size().div(total_cnt).mul(100).round(1).astype(str) + '%'

# 输出最终结果
print(res)

运行输出

A
bar     9.0%
g2g    27.7%
dtype: object

如果需要先生成全量百分比(包含B=0的占比),可以使用如下代码:

full_res = df.groupby(['A','B']).size().unstack().div(total_cnt).mul(100).round(1).astype(str) + '%'
full_res = full_res.replace('nan%', pd.NA)
print(full_res)

对应输出:

B        0      1
A                
bar  36.4%   9.0%
foo  27.3%   <NA>
g2g   <NA>  27.3%

内容的提问来源于stack exchange,提问作者rafaelcb21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:15:02