Pandas group all rows except selected

Viewed 81

I'm trying to do some select grouping and sum but keep getting error messages, clearly this is all wrong. I'd like to group all rows except a few and sum that main group. Basically, I'd like to make a pie chart showing a few slices and the main group as "other". Thanks in advance.

d = {'symbol': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'value': [5, 5, 5, 5, 1, 1, 1]}
df = pd.DataFrame(data=d)
display(df)

Output:

    symbol  value
0   a       5
1   b       5
2   c       5
3   d       5
4   e       1
5   f       1
6   g       1

Desired outcome:

    symbol  value
0   rest    20
4   e       1
5   f       1
6   g       1

Is this a somewhat right approach?

def not_in_group(sym):
    if (sym != 'e' or sym != 'f' or sym != 'g' in df['symbol']):
        return sym
    
grouped = df.groupby(not_in_group, axis=1)('value').sum()
display(grouped)
1 Answers

You can use isin and np.where to map the symbols:

mapped_symbols = np.where(df.symbol.isin(main_groups), df.symbol, 'rest')
df['value'].groupby(mapped_symbols).sum()

Output:

e        1
f        1
g        1
rest    20
Name: value, dtype: int64
Related