Skip to main content
 首页 » 编程设计

python之Pandas 用所有列的 groupby 计算 NA

2025年05月04日10rubylouvre

<分区>

This question展示了如何计算数据框中特定列 C 的 NA。如何计算所有列(不是 groupby 列)的 NA?

这是一些不起作用的测试代码:

#!/usr/bin/env python3 
 
import pandas as pd 
import numpy as np 
 
df = pd.DataFrame({'a':[1,1,2,2],  
                   'b':[1,np.nan,2,np.nan], 
                   'c':[1,np.nan,2,3]}) 
 
# result = df.groupby('a').isna().sum() 
# AttributeError: Cannot access callable attribute 'isna' of 'DataFrameGroupBy' objects, try using the 'apply' method 
 
# result = df.groupby('a').transform('isna').sum() 
# AttributeError: Cannot access callable attribute 'isna' of 'DataFrameGroupBy' objects, try using the 'apply' method 
 
result = df.isna().groupby('a').sum() 
print(result) 
# result: 
#          b    c 
# a 
# False  2.0  1.0 
 
result = df.groupby('a').apply(lambda _df: df.isna().sum()) 
print(result) 
# result: 
#    a  b  c 
# a 
# 1  0  2  1 
# 2  0  2  1 

期望的输出:

     b    c 
a 
1    1    1 
2    1    0