【问题标题】:How to count not null values on pandas column then agregating如何计算熊猫列上的非空值然后聚合
【发布时间】:2019-07-13 03:50:12
【问题描述】:

我想计算每个聚合级别的列的非空值:

import pandas as pd
import numpy as np
df = pd.DataFrame({'agr' : [1,1,1],
                'col1' : [1, np.nan, np.nan],
               'col2' : [np.nan, 2, 3] })
df.agg({'col1' : [np.sum, np.count_nonzero],
       'col2' : [ np.sum, np.count_nonzero]})

这个虚拟方法给出 3,3。 但我需要1,2。这里出了什么问题以及如何解决这个问题

【问题讨论】:

    标签: pandas aggregate-functions aggregation


    【解决方案1】:

    df.count() 默认不包含 NaN。

    import pandas as pd
    df = pd.DataFrame({'agr' : [1,1,1],
                'col1' : [1, np.nan, np.nan],
               'col2' : [np.nan, 2, 3] })
    df[['col1', 'col2']].count()
    

    -

    col1    1
    col2    2
    dtype: int64
    

    另一种方式:

    df[['col1', 'col2']].agg("count")
    

    【讨论】:

    • @Wen-Ben OP 将问题更改为 not null only
    • 这很有趣,对不起
    • 我们如何将 df,count 传递给 agr?
    • 对不起@Rocketq,你是什么意思?你能给我们举个例子吗?
    • @Rocketq 你是说这个吗? df[['col1', 'col2']].agg("count")
    【解决方案2】:

    您需要添加另一个条件notnull,因为0 != np.nan 为真

    (df.ne(0)&df.notnull()).sum()
    Out[305]: 
    agr     3
    col1    1
    col2    2
    dtype: int64
    

    更改后

    df.notnull().sum()
    Out[322]: 
    agr     3
    col1    1
    col2    2
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-14
      • 2021-01-05
      • 2021-01-22
      • 2023-03-25
      • 2021-05-26
      • 2016-04-09
      • 2020-01-10
      • 1970-01-01
      相关资源
      最近更新 更多