【问题标题】:Pandas groupby count non-null values as percentagePandas groupby 将非空值计数为百分比
【发布时间】:2017-11-08 10:14:50
【问题描述】:

鉴于此数据集,我想计算缺失的 NaN 值:

df = pd.DataFrame({'A' : [1, np.nan, 2 , 55, 6, np.nan, -17, np.nan],
                   'Team' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
                   'C' : [4, 14, 3 , 8, 8, 7, np.nan, 11],
                   'D' : [np.nan, np.nan, -12 , 12, 12, -12, np.nan, np.nan]})

具体来说,我想在“团队”列中对每个组进行计数(以百分比形式)。我可以通过这个得到原始计数:

df.groupby('Team').count()

这将获得非缺失数字的数量。我想做的是创建一个百分比,所以我不会得到原始数字,而是将它作为每个组中总条目的百分比(我不知道所有不均匀的组的大小)。我试过使用 .agg(),但我似乎无法得到我想要的。我该怎么做?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以取notnull Boolean DataFrame的mean

    In [11]: df.notnull()
    Out[11]:
           A      C      D  Team
    0   True   True  False  True
    1  False   True  False  True
    2   True   True   True  True
    3   True   True   True  True
    4   True   True   True  True
    5  False   True   True  True
    6   True  False  False  True
    7  False   True  False  True
    
    In [12]: df.notnull().mean()
    Out[12]:
    A       0.625
    C       0.875
    D       0.500
    Team    1.000
    dtype: float64
    

    并与 groupby:

    In [13]: df.groupby("Team").apply(lambda x: x.notnull().mean())
    Out[13]:
                  A         C    D  Team
    Team
    one    0.666667  0.666667  0.0   1.0
    three  0.500000  1.000000  0.5   1.0
    two    0.666667  1.000000  1.0   1.0
    

    如果不先使用set_index 进行申请,这样做可能会更快:

    In [14]: df.set_index("Team").notnull().groupby(level=0).mean()
    Out[14]:
                  A         C    D
    Team
    one    0.666667  0.666667  0.0
    three  0.500000  1.000000  0.5
    two    0.666667  1.000000  1.0
    

    【讨论】:

    • 谢谢,这两种方法我都喜欢!
    • 非常感谢 set_index() 解决方案,特别是它为我当前的项目救了命!
    【解决方案2】:

    根据自己的代码添加div(df.groupby('Team').size(),0)

    df.groupby('Team').count().div(df.groupby('Team').size(),0)
    Out[190]: 
                  A         C    D
    Team                          
    one    0.666667  0.666667  0.0
    three  0.500000  1.000000  0.5
    two    0.666667  1.000000  1.0
    

    【讨论】:

    • 之前没见过div()函数;这真的很有用。谢谢!
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 2022-11-21
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2015-04-25
    相关资源
    最近更新 更多