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

如何用Pandas按列统计全数据集内Not Reported的数量?

问题:统计Pandas数据集中各列“Not Reported”的出现次数

我是Pandas新手,学习过程中已使用count()、value_counts()按列统计值,但遇到了问题。我有一份车祸报告数据集,其中空值已替换为“Not Reported”,想要按列统计整个数据集中该值的单元格数量,期望得到对应格式的输出:

数据集示例

LocationSeverityTimeOutcomeSubstance UsedTraffic Signal
New YorkLevel 1Not ReportedCasualtyAlcoholRed
TexasNot Reported7:00:00Minor InjuryNot ReportedGreen
Not ReportedLevel 4Not ReportedNot ReportedSmokingYellow

期望输出

ColumnValueCount
LocationNot Reported1
SeverityNot Reported1
TimeNot Reported2
OutcomeNot Reported1
Substance UsedNot Reported1
Traffic SignalNot Reported0

请问是否有方法实现该需求?


解决方案

这里提供两种简洁的实现方式,都能快速得到你想要的表格格式:

方法一:高效列匹配统计

直接对每列计算等于"Not Reported"的单元格数量,再整理成目标格式:

import pandas as pd

# 假设你的数据集名为df
result = df.apply(lambda col: col.eq("Not Reported").sum()).reset_index()
result.columns = ["Column", "Count"]
result["Value"] = "Not Reported"
# 调整列顺序匹配期望输出
result = result[["Column", "Value", "Count"]]

# 输出Markdown格式表格(需先安装tabulate:pip install tabulate)
print(result.to_markdown(index=False))

逻辑说明:

  • col.eq("Not Reported").sum():对每一列,逐单元格匹配"Not Reported",求和得到该列的总次数
  • reset_index():将原列名从索引转为普通列,命名为"Column"
  • 添加固定列"Value",值统一为"Not Reported"
  • 调整列顺序后,用to_markdown直接输出符合要求的表格

方法二:循环遍历列统计

如果更习惯循环逻辑,可以遍历每一列,用value_counts获取目标值的次数(不存在则返回0):

import pandas as pd

result_list = []
for col_name in df.columns:
    # 获取当前列"Not Reported"的次数,没有则返回0
    count = df[col_name].value_counts().get("Not Reported", 0)
    result_list.append({
        "Column": col_name,
        "Value": "Not Reported",
        "Count": count
    })

result_df = pd.DataFrame(result_list)
print(result_df.to_markdown(index=False))

两种方法都能生成你期望的输出格式,测试示例数据集时,会得到完全匹配的结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:10:33