如何用Pandas按列统计全数据集内Not Reported的数量?
问题:统计Pandas数据集中各列“Not Reported”的出现次数
我是Pandas新手,学习过程中已使用count()、value_counts()按列统计值,但遇到了问题。我有一份车祸报告数据集,其中空值已替换为“Not Reported”,想要按列统计整个数据集中该值的单元格数量,期望得到对应格式的输出:
数据集示例
| Location | Severity | Time | Outcome | Substance Used | Traffic Signal |
|---|---|---|---|---|---|
| New York | Level 1 | Not Reported | Casualty | Alcohol | Red |
| Texas | Not Reported | 7:00:00 | Minor Injury | Not Reported | Green |
| Not Reported | Level 4 | Not Reported | Not Reported | Smoking | Yellow |
期望输出
| Column | Value | Count |
|---|---|---|
| Location | Not Reported | 1 |
| Severity | Not Reported | 1 |
| Time | Not Reported | 2 |
| Outcome | Not Reported | 1 |
| Substance Used | Not Reported | 1 |
| Traffic Signal | Not Reported | 0 |
请问是否有方法实现该需求?
解决方案
这里提供两种简洁的实现方式,都能快速得到你想要的表格格式:
方法一:高效列匹配统计
直接对每列计算等于"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
相关产品推荐
相关产品推荐

