I would like to create an additional column with averages based on column A, using dynamic ranges.
import numpy as np
import pandas as pd
test = {'A' : [100, 120, 70, 300, 190, 70, 300, 190, 70],
'B' : [80, 50, 64, 288, 172, 64, 288, 172, 64],
'C' : ['NO', 'NO', 'YES', 'NO', 'YES', 'YES', 'NO', 'YES', 'YES'],
'D' : [0, 1, 0, 3, 2, 2, 3, 1, 4] }
df = pd.DataFrame(data=test)
A B C D
0 100 80 NO 0
1 120 50 NO 1
2 70 64 YES 0
3 300 288 NO 3
4 190 172 YES 2
5 70 64 YES 2
6 300 288 NO 3
7 190 172 YES 1
8 70 64 YES 4
When item in column C is YES get average value from dynamic range in column A by using value in column D as starting row index and row index of current row -1 as highest row index.
Below is the outcome I am seeking to achieve.
A B C D Dyn_Ave
0 100 80 NO 0 NaN
1 120 50 NO 1 NaN
2 70 64 YES 0 110
3 300 288 NO 3 NaN
4 190 172 YES 2 185
5 70 64 YES 2 187
6 300 288 NO 3 NaN
7 190 172 YES 1 175
8 70 64 YES 4 188
My attempt at creating the column has lead me to a np.where approach, although I am coming across the following error - TypeError: Cannot index by location index with a non-integer key
df['Dyn_Ave'] = np.where(df['C'] == 'YES', df['A'].iloc[df['D']:df.loc['C'][-1]].mean(), np.nan)