【问题标题】:Groupby a column and make a new column while aggregating over conditional statements在聚合条件语句时按列分组并创建一个新列
【发布时间】:2020-02-07 01:12:21
【问题描述】:

我想按颜色分组,计算一列中该颜色的出现次数并创建一个新列within_range,其中包含以下情况的计数: min_amount <= amount <= max_amount

df = pd.DataFrame({'color': ['red', 'yellow', 'blue', 'red','yellow'], 
                   'amount': [0.5, 0.25, 0.125, 0.9, 0.8],
                   'min_amount': [0, 0.2, 0.1, 0.5, 0.7],
                   'max_amount':[1, 0.7, 0.2, 0.6, 0.9]})

可以使用以下方法计算出现次数:

df.groupby('color').agg({'color':'count'}) 但是如何得到预期的结果?

预期结果:

color         count    within_range
red             2            1
yellow          2            2
blue            1            1

【问题讨论】:

    标签: python pandas aggregate pandas-groupby


    【解决方案1】:

    您只需要定义within_rangeseries 和 groupby:

    df['within_range'] = (df['amount'].le(df['max_amount']) 
                          & df['amount'].ge(df['min_amount'])
                         )
    
    (df.groupby('color')['within_range']
       .agg(count='count',winthin_range='sum')
    )
    

    输出:

            count  winthin_range
    color                       
    blue        1            1.0
    red         2            1.0
    yellow      2            2.0
    

    【讨论】:

    • 当我使用df['within_range'] = ((df['min_amount'] <= df['amount'] <= df['max_amount'])) 时,出现以下错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 如果我不想使用&,我可以不这样做吗?
    • 不,我不认为你可以用 pandas 系列做到这一点。
    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多