I'd like to create a new column with pandas groupby division between two columns excluding the current row. Sample dataset:
import pandas as pd
df = pd.DataFrame({'Group':['A', 'A', 'A', 'B', 'B'],
'Col_1':[100, 200, 300, 400, 500],
'Col_2':[55, 66, 77, 88, 99]})
| Group | Col_1 | Col_2 |
|---|---|---|
| A | 100 | 55 |
| A | 200 | 66 |
| A | 300 | 77 |
| B | 400 | 88 |
| B | 500 | 99 |
I'd like to create a new column called "Div_excl"
Methodology: Take the sum of Col_1 and Col_2 by each Group, then exclude the current row value within each groupby sum, then do the division
| Group |Col_1 | Col_2 | Div_exclud |
|-------|------|--------|---------------------------------------|
| A | 100 | 55 |[(55+66+77)-55)] / [(100+200+300)-100)]|
| A | 200 | 66 |[(55+66+77)-66)] / [(100+200+300)-200)]|
| A | 300 | 77 |[(55+66+77)-77)] / [(100+200+300)-300)]|
| B | 400 | 88 | [(88+99)-88)] / [(400+500)-400)] |
| B | 500 | 99 | [(88+99)-99)] / [(400+500)-500)] |
I have tried the following, but it doesn't look right:
df.groupby('Group').apply(lambda x: (df['Col_2'].sum()-x)/(df['Col_1'].sum()-x))