Reputation: 3713
Consider dataframe:
df = pd.DataFrame({
"a": [None, None, None, None, 1, 2, -1, 0, 1],
"b": [5, 4, 6, 7, None, None, None, None, None]
})
>> a b
0 NaN 5.0
1 NaN 4.0
2 NaN 6.0
3 NaN 7.0
4 1.0 NaN
5 2.0 NaN
6 -1.0 NaN
7 0.0 NaN
8 1.0 NaN
For each missing value in b I want to take average of previous 4 values plus value in a with the same index. For example, after 7:
4: (5 + 4 + 6 + 7) / 4 + 1 = 6.5
5: (6.5 + 4 + 6 + 7) / 4 + 2 = 7.88
...
The result dataframe should be:
>> a b
0 NaN 5.00
1 NaN 4.00
2 NaN 6.00
3 NaN 7.00
4 1.0 6.50
5 2.0 7.88
6 -1.0 5.84
7 0.0 6.80
8 1.0 7.76
How to achieve that?
Upvotes: 2
Views: 552
Reputation: 323226
Using for loop here, panda is not row-wise , they can not using the previous calculated value for the future calculation.(vectorized)
l=[]
for x ,y in zip(*df.values.T.tolist()):
if len(l)<4:
l.append(y)
else:
l.append(sum(l[-4:])/4+x)
l
Out[188]: [5.0, 4.0, 6.0, 7.0, 6.5, 7.875, 5.84375, 6.8046875, 7.755859375]
df.b=l
df
Out[190]:
a b
0 NaN 5.000000
1 NaN 4.000000
2 NaN 6.000000
3 NaN 7.000000
4 1.0 6.500000
5 2.0 7.875000
6 -1.0 5.843750
7 0.0 6.804688
8 1.0 7.755859
Upvotes: 3