I've a pandas dataset with open, high, low, close and key column. Now I want to group the dataset by key and calculate pivot with the formula - (high + low + close) / 3. Upto this I'm able to do. But the requirement is to shift the calculated data to next group which I'm unable to code.
I'm able to group the dataset by key column and able to calculate pivot data.
import pandas as pd
data = pd.DataFrame([[110, 115, 105, 111, 1],[11, 16, 6, 12, 1],[12, 17, 7, 13, 1],[12, 16, 6, 11, 2],[9, 13, 4, 13, 2],[13, 18, 9, 12, 3],[14, 16, 10, 13, 3]], columns=["open","high","low","close","key"])
data['p'] = (data.high.groupby(data.key).transform('max') + data.low.groupby(data.key).transform('min') + data.close.groupby(data.key).transform('last')) / 3
print(data)
Currently I'm getting below output.
open high low close key p
0 110 115 105 111 1 44.666667
1 11 16 6 12 1 44.666667
2 12 17 7 13 1 44.666667
3 12 16 6 11 2 11.000000
4 9 13 4 13 2 11.000000
5 13 18 9 12 3 13.333333
6 14 16 10 13 3 13.333333
But after shifting value to next group the expected output should be as mentioned below.
open high low close key p
0 110 115 105 111 1 NaN
1 11 16 6 12 1 NaN
2 12 17 7 13 1 NaN
3 12 16 6 11 2 44.666667
4 9 13 4 13 2 44.666667
5 13 18 9 12 3 11.000000
6 14 16 10 13 3 11.000000
Instead 3 dimes groupby use GroupBy.agg
with dictionary, then sum
values per rows and divide 3. Last use Series.map
with Series.shift
ed values for new column:
s = data.groupby('key').agg({'low':'min','high':'max','close':'last'}).sum(axis=1) / 3
data['s'] = data['key'].map(s.shift())
print(data)
open high low close key s
0 110 115 105 111 1 NaN
1 11 16 6 12 1 NaN
2 12 17 7 13 1 NaN
3 12 16 6 11 2 44.666667
4 9 13 4 13 2 44.666667
5 13 18 9 12 3 11.000000
6 14 16 10 13 3 11.000000