You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame的pd.count()结果小于1时插入零值

核心原因

筛选不存在的分类(例如Jim对应的Bad结果)时得到的是空DataFrame,即使插入Count列,该DataFrame依然没有行数据,拼接后自然不会展示计数为0的条目。

方案1:修改原有循环逻辑

在判断到计数为0时,手动构造对应行补充到结果中:

import pandas as pd

data = {'Person': ['Jim', 'Jim', 'Jim', 'Jim', 'Jim', 'Bob','Bob','Bob','Bob','Bob',], 'Result': ['Good', 'Good','Good','Good','Good','Good','Bad','Good','Bad','Bad',]}
dtf = pd.DataFrame.from_dict(data)

names = ['Jim','Bob']
result_types = ['Good', 'Bad']
append = []
for i in names:
    res_list = []
    for res_type in result_types:
        filtered = dtf[(dtf['Person']==i) & (dtf['Result']==res_type)]
        cnt = filtered['Result'].count()
        filtered.insert(2, "Count", cnt)
        # 计数为0时手动构造行
        if cnt == 0:
            filtered = pd.DataFrame([[i, res_type, 0]], columns=['Person', 'Result', 'Count'])
        res_list.append(filtered)
    res = pd.concat(res_list)
    append.append(res)
    print(res.reset_index(drop=True))

运行输出和你预期的效果完全一致。

方案2:Pandas原生向量化实现(无循环,性能更优)

用分组计数+全分类补全的逻辑,代码更简洁:

import pandas as pd

data = {'Person': ['Jim', 'Jim', 'Jim', 'Jim', 'Jim', 'Bob','Bob','Bob','Bob','Bob',], 'Result': ['Good', 'Good','Good','Good','Good','Good','Bad','Good','Bad','Bad',]}
dtf = pd.DataFrame.from_dict(data)

# 统计每个用户每个结果的计数
count_df = dtf.groupby(['Person', 'Result']).size().rename('Count')
# 生成全量用户+结果的组合索引,补全缺失的分类
all_combinations = pd.MultiIndex.from_product(
    [dtf['Person'].unique(), dtf['Result'].unique()],
    names=['Person', 'Result']
)
count_df = count_df.reindex(all_combinations, fill_value=0).reset_index()
# 合并回原表,缺失的分类行自动补全
final_df = dtf.merge(count_df, on=['Person', 'Result'], how='right').sort_values(['Person', 'Result'], ascending=[True, False])

# 按用户分组打印
for person, group in final_df.groupby('Person'):
    print(group.reset_index(drop=True))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:36:06