import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(10, size = (20, 1)),columns=['A'])
s = [0,0,1,0,0,0,2,0,1,2,0,0,1,0,0,2,0,1,0,0]
df['B'] = s
>>> print(df)
A B
0 4 0
1 1 0
2 6 1
3 3 0
4 4 0
5 3 0
6 1 2
7 4 0
8 2 1
9 3 2
10 4 0
11 9 0
12 4 1
13 0 0
14 6 0
15 6 2
16 9 0
17 2 1
18 9 0
19 3 0
My goal is add two new columns, namely 'C_Max' and 'D_Mean'.
If the value of column B is 1, then the index from ‘1’ to the next occurrence of ‘2’ is [2:6], put the maximum value between [2:6] in column A into column C_Max at the same position with B1's 1, i.e. [2] in column C_Max, then average all the numbers [2:6] in column A, and put the result in the same position as column B in column D_Mean, that is, [2] in column D_mean. And so on.
Ignored if 2 does not appear after 1.The values of other cells in columns C_Max and D_min do not matter.
Desired output:
>>> df
A B C_Max D_Mean
0 4 0 NaN NaN
1 1 0 NaN NaN
2 6 1 6.0 3.4
3 3 0 NaN NaN
4 4 0 NaN NaN
5 3 0 NaN NaN
6 1 2 NaN NaN
7 4 0 NaN NaN
8 2 1 3.0 2.5
9 3 2 NaN NaN
10 4 0 NaN NaN
11 9 0 NaN NaN
12 4 1 6.0 4.0
13 0 0 NaN NaN
14 6 0 NaN NaN
15 6 2 NaN NaN
16 9 0 NaN NaN
17 2 1 NaN NaN
18 9 0 NaN NaN
19 3 0 NaN NaN
