Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 如何在数据帧中按行计算组中的空值_Pandas - Fatal编程技术网

Pandas 如何在数据帧中按行计算组中的空值

Pandas 如何在数据帧中按行计算组中的空值,pandas,Pandas,根据本主题https://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-per-group-and-other-statistics-in-pandas-group-by我想在DataFrame中再添加一个stat-count空值(也称为NaN): tdf = pd.DataFrame(columns = ['indicator', 'v1', 'v2', 'v3', 'v4'],

根据本主题
https://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-per-group-and-other-statistics-in-pandas-group-by
我想在DataFrame中再添加一个stat-count空值(也称为NaN):

tdf = pd.DataFrame(columns = ['indicator', 'v1', 'v2', 'v3', 'v4'], 
                   data = [['A', '3', pd.np.nan, '4', pd.np.nan ],
                           ['A', '3', '4', '4', pd.np.nan ],
                           ['B', pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan],
                           ['B', '1', None, pd.np.nan, None ],
                           ['C', '9', '7', '4', '0']])
我想用这样的东西:

tdf.groupby('indicator').agg({'indicator':['count']})

但通过添加nulls计数器,将其放在单独的列中,如:

tdf.groupby('indicator').agg({'indicator':['count','isnull']})

现在,我得到错误:
AttributeError:无法访问“SeriesGroupBy”对象的可调用属性“isnull”,请尝试使用“apply”方法

我如何在此处访问此函数或将其与功能一起使用

预期产出将是:

          indicator      nulls
              count      count
indicator          
A                 2          3
B                 2          7
C                 1          0
请注意,
pd.np.nan
的工作方式与
None
相同。

首先用count by
sum
检查所有缺失值,然后用
sum
聚合
count

df = tdf.set_index('indicator').isnull().sum(axis=1).groupby(level=0).agg(['count','sum'])
print (df)
           count  sum
indicator            
A              2    3
B              2    7
C              1    0
详细信息

print (tdf.set_index('indicator').isnull().sum(axis=1))
indicator
A    2
A    1
B    4
B    3
C    0
dtype: int64
另一种解决方案是将函数用于:


我自己也找到了几乎令人满意的答案:(缺点:有点太复杂了)。例如,在R中,我会在
is.na(df)
矩阵上使用
RowSums
。很遗憾,这是一种很好的方式,但更多的是编码

def count_nulls_rowwise_by_group(tdf, group):
    cdf = pd.concat([tdf[group], pd.isnull(tdf).sum(axis=1).rename('nulls')], axis=1)
    return cdf.groupby(group).agg({group: 'count', 'nulls': 'sum'}).rename(index=str, columns={group: 'count'})
count\u nulls\u rowwise\u by\u group(tdf)

给出:

Out[387]: 
           count  nulls
indicator              
A              2      3
B              2      7
C              1      0

我喜欢你的第一个解决方案——它比我的短两倍。
Out[387]: 
           count  nulls
indicator              
A              2      3
B              2      7
C              1      0