【问题标题】:Count NaN Single Column with Multiple Conditions in Other Columns在其他列中计算具有多个条件的 NaN 单列
【发布时间】:2021-07-02 18:34:27
【问题描述】:

我似乎无法通过尝试许多不同的事情来解决这个问题,而且我在网络上显然没有找到答案。我的数据在单列“数据”中具有值,我需要根据其他两列中的条件分组来求和或计算该列中 NaN 的出现次数,例如下面的数据:

    site     data      day     month   year
0   Red      NaN        20     1       2020
1   Red      5.6        31     1       2020
2   Red      NaN         6     1       2020
3   Red      NaN         9     2       2020
3   Blue     4.5        14     1       2020
4   Blue     6.2        19     2       2020
5   Blue     NaN        11     2       2020

结果应该是这样的:

   site    month    count    sumNaN  
0  Red     1        3        2
1  Red     2        1        1
2  Blue    1        1        0
3  Blue    2        2        1

非常感谢。

【问题讨论】:

    标签: pandas group-by count multiple-columns nan


    【解决方案1】:

    试试:

    (df.assign(data=df['data'].isna())
       .groupby(['site','month'])
       ['data'].agg(['count','sum'])
       .reset_index()
    )
    

    输出:

       site  month  count  sum
    0  Blue      1      1    0
    1  Blue      2      2    1
    2   Red      1      3    2
    3   Red      2      1    1
    

    【讨论】:

      【解决方案2】:

      您可以在agg 中使用命名聚合:

      (df.groupby(['site', 'month'], as_index = False)
         .agg(count=('data', 'size'), 
              sumNaN=('data', lambda df: df.isna().sum())
              )
       )
      
         site  month  count  sumNaN
      0  Blue      1      1     0.0
      1  Blue      2      2     1.0
      2   Red      1      3     2.0
      3   Red      2      1     1.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-26
        • 2013-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        • 2020-01-20
        相关资源
        最近更新 更多