pandas: how to aggregate a subset of groupby rows into a single row?

Viewed 1635

Here's what I'd like to do given the following input:

pd.DataFrame({'cat':['A','B','C','B','C','D','C','E'], 'value':[3,6,7,7,9,8,3,1]})

cat    value
A          3
B          6
C          7
B          7
C          9
D          8
C          3
E          1
  1. Group by cat and sort descending:

    df.groupby('cat').sum().sort_values('value', ascending=False)
    
    cat    sum
    C       19
    B       13
    D        8
    A        3
    E        1
    
  2. Leave rows that cumulatively add up to less than 90% as is, but the remaining rows combine into a single new category 'Other':

    cat    sum
    C       19
    B       13
    Other   12
    

How do I do the last step?

1 Answers
Related