I have the following dataframe:
d = pd.DataFrame({'UNIQUE_KEY': [1, 2, 3, 4], 'TRANSFORMATION': ['P', 'D', 'N', 'P'],
'DIM_1': ['Y', 'N', 'N', 'Y'], 'DIM_2': ['N', 'N', 'N', 'Y'], 'DIM_3': ['Y', 'Y', 'N', 'Y']})
UNIQUE_KEY TRANSFORMATION DIM_1 DIM_2 DIM_3
0 1 P Y N Y
1 2 D N N Y
2 3 N N N N
3 4 P Y Y Y
I want to perform several groupby and aggregate operations in order to get the following output dataframe:
DIM DIM_VALUE TTL_CASES % CASES % D % N % P
0 DIM_1 'Y' 2 50 0 0 100
1 DIM_1 'N' 2 50 50 50 0
2 DIM_2 'Y' 1 25 0 0 100
3 DIM_2 'N' 3 75 33.3 33.3 33.3
4 DIM_3 'Y' 3 75 33.3 0 66.6
5 DIM_3 'N' 1 25 0 100 0
Where
DIMis a column with each ofDIM_1,2,3DIM_VALUEis a grouped column based on the values of eachDIM_1,2,3TTL_CASESis a column with the count ofUNIQUE_KEYgrouped byDIMandDIM_1,2,3PCT_CASESis the percentage of each row ofTTL_CASES%D,%P,%Nare the percentages ofTRANSFORMATIONofUNIQUE_KEYbased on the the grouped byDIMandDIM_1,2,3
What I have is the following:
P = d.groupby('TRANSFORMATION')['UNIQUE_KEY'].count().reset_index()
P['Percentage'] = 100 * P['UNIQUE_KEY'] / P['UNIQUE_KEY'].sum()
which gives me the percentage of each value in TRANFORMATION but how do I do this for each dimension and get an output dataframe in the format I want?
Thanks in advance!