I am trying to get various combinations for the data in three columns, and while doing so, I also want to aggregate (sum) the values.
My data is shown as below and following that is my sample output :
Dim1 Dim2 Dim3 Spend
A X Z 100
A Y Z 200
B X Z 300
B Y Z 400
Sample output :
Dim 1 Dim 2 Dim 3 Spend
A NaN NaN 300
A X NaN 100
A Y NaN 200
A NaN Z 300
B NaN NaN 700
B X NaN 300
B Y NaN 400
B NaN Z 700
NaN X Z 400
NaN Y Z 600
NaN NaN Z 1000
NaN X NaN 400
NaN Y NaN 600
A X Z 100
A Y Z 200
B X Z 300
B Y Z 400
Dim1, Dim2, Dim3 are categorical variables and Spend is a value/metric. We need to find total of Spend on all the possible combinations of the categorical variables and this part I am able to achieve using itertools.combinations(). Now, not only for three columns, we can also get the combinations for any number of such variables like Dim1, Dim2, Dim3 .. Dim 30 and so on.
My problem is I am unable to aggregate on the same, like for example, in row 12, for the Spend value for category Z, we are performing the sum() of all the values where Z has appeared in the main data, hence the value 1000. How do we achieve that for of aggregates?
Reproducible data :
data = pd.DataFrame({'Dim1': ['A', 'A', 'B', 'B'],
'Dim2': ['X', 'Y', 'X', 'Y'],
'Dim3': ['Z', 'Z', 'Z', 'Z'],
'Spend': [100, 200, 300, 400]})