I have the following data frame:
d = {'T': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Val1': [10, np.NaN, 14, np.NaN, np.NaN, np.NaN, 20, np.NaN, np.NaN, 30]}
df = pd.DataFrame(data=d)
T Val1
1 10.0
2 NaN
3 14.0
4 NaN
5 NaN
6 NaN
7 20.0
8 NaN
9 NaN
10 30.0
I want to fill the NaN with different values depending on certain conditions:
- If the value
Vis NaN and ifV+1andV-1are not NaN thenV=np.mean([V+1, V-1]) - If the values
VandV+1are NaN and ifV-1andV+2are not NaN then I want to fill them following this formula:V=np.cbrt([(V-1)*(V-1)*(V+2)])ANDV+1=np.cbrt([(V-1)*(V+2)*(V+2)]) - Other NaN should be removed
So the wanted datatable should look like:
T Val1
1 10.0
2 12.0
3 14.0
7 20.0
8 22.89
9 26.20
10 30.0
I was able to do the V=np.mean([V+1, V-1]) by the following command:
df1 = pd.concat([df.ffill(), df.bfill()]).groupby(level=0).mean()
T Val1
1 10.0
2 12.0
3 14.0
4 17.0
5 17.0
6 17.0
7 20.0
8 25.0
9 25.0
10 30.0
But I don't know how to incorporate the different conditions.
I tried using np.select() but I can't find a way to recover following and previous value and add them to the conditions.
Thanks a lot