I have a dataset which looks like this:
import pandas as pd, numpy as np
df = pd.DataFrame([[1,0,3,0], [5,6,7,8], [9,10,11,12], [11, 14,15,16], [0,0,19,0]], columns=['a','b','c','d'])
So what I want to do is:
- in the last row, wherever value is 0s, replace with the mean of previous three rows of the same column
- if the value is not 0, then leave it as it is
- Also all other 0's elsewhere should remain 0 only.
So the end result should look something like this:
a b c d
1 0 3 0
5 6 7 8
9 10 11 12
13 14 15 16
9 10 19 12
Here, all three 0s are replaced with the previous three values' mean. And 19 remains as it is.
What I am trying to do is:
if (df.iloc[-1].any()==0):
df.iloc[-1] = df[-4:-1].mean()
else:
pass
This did not change the values and no error was returned as well. What am I doing wrong here?