【问题标题】:Pandas groupby multiple columns to compare valuesPandas 按多列分组以比较值
【发布时间】:2022-06-22 22:33:14
【问题描述】:

我的 df 看起来像这样:(df 中还有几十个其他列,但这是我关注的三个)

Param    Value      Limit  
A        1.50       1
B        2.50       1
C        2.00       2
D        2.00       2.5
E        1.50       2

我正在尝试使用 pandas 来计算每个 [Param] 有多少 [Value] 小于 [Limit],希望得到这样的列表:

Param    Count       
A        1
B        1       
C        1       
D        0       
E        0       

我尝试了几种方法,第一种是

value_count = df.loc[df['Value'] < df['Limit']].count() 但这只是给出了 df 中每列的完整计数。

我还尝试了 groupby 函数,我认为这可能是正确的想法,方法是使用所选列创建 df 的子集

df_below_limit = df[df['Value'] < df['Limit']]
df_below_limit.groupby('Param')['Value'].count()

这几乎是我想要的,但它不包括我也需要的值。不知道如何获取我需要的列表。

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    假设您想要每个参数的计数,您可以使用:

    out = df['Value'].ge(df['Limit']).groupby(df['Param']).sum()
    

    输出:

    Param
    A    1
    B    2
    C    1
    D    0
    E    0
    dtype: int64
    

    使用的输入(例如重复的“B”行):

      Param  Value  Limit
    0     A    1.5    1.0
    1     B    2.5    1.0
    2     B    2.5    1.0
    3     C    2.0    2.0
    4     D    2.0    2.5
    5     E    1.5    2.0
    
    作为数据帧
    df['Value'].ge(df['Limit']).groupby(df['Param']).sum().reset_index(name='Count')
    
    # or
    
    df['Value'].ge(df['Limit']).groupby(df['Param']).agg(Count='sum').reset_index()
    

    输出:

      Param  Count
    0     A      1
    1     B      2
    2     C      1
    3     D      0
    4     E      0
    

    【讨论】:

      【解决方案2】:

      用途:

      In [1494]: res = df[df.Value.lt(df.Limit)].groupby('Param', as_index=False).size()
      
      In [1500]: remaining_params = np.setdiff1d(df.Param.unique(), res.Param)
      
      In [1508]: res = pd.concat([res, pd.DataFrame({'Param': remaining_params, 'size':[0] * len(remaining_params)})])
      
      In [1509]: res
      Out[1509]: 
        Param  size
      0     D     1
      1     E     1
      0     A     0
      1     B     0
      2     C     0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 1970-01-01
        • 1970-01-01
        • 2020-08-30
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        相关资源
        最近更新 更多