I have a dataset, df, where I would like to pivot its rows to column titles and create a running total:
Data
cons_power cons_count id date r_power r_count d_power d_count
500 20 aa q122 50 2 20 1
0 0 aa q222 20 1 0 0
1000 80 bb q122 0 0 50 3
0 0 bb q222 100 5 0 0
Desired
id q122_power q122_count q222_power q222_count
aa 530 21 550 22
bb 950 77 1050 82
Logic
We start w cons_power value of 500 for id 'aa' for q122 and we add r_power value of 50, and subtract d_power value of 20 which gives us: 530 value
We then carry on the value of 530 as our next baseline value for q222 process of adding r_power and subtracting d_power = 550
Same concept is used for the count. (start w a count of 20 for 'aa' q122 and add 2 and subtract 1) giving us: 21 value
We then carry on the value of 21 as our next baseline value for q222 process of adding r_count and subtracting d_count = 22
Doing
df['q122_power'] = df['r_power'].add(df.groupby('id', 'date')
['r_power'].cumsum()).sub(df.groupby('id', 'date')['d_power'].cumsum())
df['q222_power'] = df['r_power'].add(df.groupby('id', 'date')
['r_power'].cumsum()).sub(df.groupby('id', 'date')['d_power'].cumsum())
df['q122_count'] = df['r_count'].add(df.groupby('id', 'date')
['r_count'].cumsum()).sub(df.groupby('id', 'date')['d_count'].cumsum())
df['q222_count'] = df['r_count'].add(df.groupby('id', 'date')
['r_count'].cumsum()).sub(df.groupby('id', 'date')['d_count'].cumsum())
Trying to find a more elegant way of producing the desired output. I have been able to solve the grouping and calculations but unsure on how to incorporate the pivot steps within the script. Any suggestion is appreciated.