I would like to create multiple columns which show the row-wise cumulative mean for grouped columns. Here is some sample data:
import pandas as pd
data = [[1, 4, 6, 10, 15, 40, 90, 100], [2, 5, 3, 11, 25, 50, 90, 120], [3, 7, 9, 14, 35, 55, 100, 120]]
df = pd.DataFrame(data, columns=['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4'])
a1 a2 a3 a4 b1 b2 b3 b4
0 1 4 6 10 15 40 90 100
1 2 5 3 11 25 50 90 120
2 3 7 9 14 35 55 100 120
What I want is to generate new columns like this:
- New column
a1_2is calculated by the mean of columnsa1anda2row-wise. - New column
a1_3is calculated by the mean of columnsa1,a2anda3row-wise. - New column
a1_4is calculated by the mean of columnsa1,a2,a3anda4row-wise.
The same should happen for the grouped columns with b. Of course you can do this manually, but this is not ideal when you have too many variables. Here is the expected output:
df['a1_2'] = df[['a1', 'a2']].mean(axis=1)
df['a1_3'] = df[['a1', 'a2', 'a3']].mean(axis=1)
df['a1_4'] = df[['a1', 'a2', 'a3', 'a4']].mean(axis=1)
df['b1_2'] = df[['b1', 'b2']].mean(axis=1)
df['b1_3'] = df[['b1', 'b2', 'b3']].mean(axis=1)
df['b1_4'] = df[['b1', 'b2', 'b3', 'b4']].mean(axis=1)
a1 a2 a3 a4 b1 b2 b3 b4 a1_2 a1_3 a1_4 b1_2 b1_3 b1_4
0 1 4 6 10 15 40 90 100 2.5 3.666667 5.25 27.5 48.333333 61.25
1 2 5 3 11 25 50 90 120 3.5 3.333333 5.25 37.5 55.000000 71.25
2 3 7 9 14 35 55 100 120 5.0 6.333333 8.25 45.0 63.333333 77.50
So I was wondering if there is some automatic way of doing this?