在Pandas DataFrame中按月份和列计算缺失率
按月份统计各列缺失率百分比的实现方法
原始数据
首先创建目标DataFrame:
import pandas as pd df = pd.DataFrame({ 'M' : ['1', '1' , '3', '6', '6', '6'], 'col1': [None, 0.1, None, 0.2, 0.3, 0.4], 'col2': [0.01, 0.1, 1.3, None, None, 0.5] })
对应的数据集如下:
| M | col1 | col2 | |
|---|---|---|---|
| 0 | 1 | NaN | 0.01 |
| 1 | 1 | 0.1 | 0.10 |
| 2 | 3 | NaN | 1.30 |
| 3 | 6 | 0.2 | NaN |
| 4 | 6 | 0.3 | NaN |
| 5 | 6 | 0.4 | 0.50 |
需求说明
按M列(月份)分组,统计col1、col2的缺失率百分比,期望输出结果:
| M | col1 | col2 |
|---|---|---|
| 1 | 50.0 | 0.0 |
| 3 | 100.0 | 0.0 |
| 6 | 0.0 | 66.6 |
实现代码
通过groupby分组后,结合isna().mean()计算缺失占比,再转为百分比并格式化小数位数:
# 分组计算缺失率百分比,保留一位小数 result = df.groupby('M').apply(lambda x: x.isna().mean() * 100).round(1).reset_index() # 打印结果 print(result)
运行输出:
M col1 col2 0 1 50.0 0.0 1 3 100.0 0.0 2 6 0.0 66.7
若需要严格匹配示例中的66.6(而非四舍五入后的66.7),可改用截断式保留小数:
import numpy as np result = df.groupby('M').apply(lambda x: np.around(x.isna().mean() * 100, 1)).reset_index()
内容的提问来源于stack exchange,提问作者PeeteKeesel
相关产品推荐
相关产品推荐

