【问题标题】:Display missing values of specific column based on another specific column根据另一个特定列显示特定列的缺失值
【发布时间】:2017-01-08 20:47:21
【问题描述】:

这是我的问题

假设我在数据框中有 2 列,如下所示:

 Type   | Killed
_______ |________
 Dog        1
 Dog       nan
 Dog       nan
 Cat        4
 Cat       nan
 Cow        1
 Cow       nan

我想根据类型在 Killed 中显示所有缺失值并统计它们

我的愿望结果是这样的:

Type | Sum(isnull)
Dog       2
Cat       1
Cow       1

还有什么可以显示的吗?

【问题讨论】:

    标签: python pandas dataframe multiple-columns nan


    【解决方案1】:

    isnullnotnull 我都可以找到你

    isnull = np.where(df.Killed.isnull(), 'isnull', 'notnull')
    df.groupby([df.Type, isnull]).size().unstack()
    

    【讨论】:

      【解决方案2】:

      您可以将boolean indexingvalue_counts 一起使用:

      print (df.ix[df.Killed.isnull(), 'Type'].value_counts().reset_index(name='Sum(isnull)'))
      
        index  Sum(isnull)
      0   Dog            2
      1   Cow            1
      2   Cat            1
      

      或者聚合size,好像更快:

      print (df[df.Killed.isnull()]
                  .groupby('Type')['Killed']
                  .size()
                  .reset_index(name='Sum(isnull)'))
      
        Type  Sum(isnull)
      0  Cat           1
      1  Cow           1
      2  Dog           2
      

      时间安排

      df = pd.concat([df]*1000).reset_index(drop=True)
      
      In [30]: %timeit (df.ix[df.Killed.isnull(), 'Type'].value_counts().reset_index(name='Sum(isnull)'))
      100 loops, best of 3: 5.36 ms per loop
      
      In [31]: %timeit (df[df.Killed.isnull()].groupby('Type')['Killed'].size().reset_index(name='Sum(isnull)'))
      100 loops, best of 3: 2.02 ms per loop
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-10
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        相关资源
        最近更新 更多