here is my sample df:
JavaScript
x
12
12
1
x y
2
0 0 1.1
3
1 1 3.9
4
2 2 11.2
5
3 3 21.5
6
4 4 34.8
7
5 5 51.0
8
6 6 70.2
9
7 7 NaN
10
8 8 NaN
11
9 9 NaN
12
If I would like to replace the NaN values and ffill the last number (70.2 – in this case), I would simply apply:
JavaScript
1
2
1
df['y'].ffill(inplace=True)
2
However, what if I would like to apply a custom function instead of ffill() method: For instance, I need the NaN values of y column to be replaced with “2 * x^2”. See the desired output df:
JavaScript
1
12
12
1
x y
2
0 0 1.1
3
1 1 3.9
4
2 2 11.2
5
3 3 21.5
6
4 4 34.8
7
5 5 51.0
8
6 6 70.2
9
7 7 98
10
8 8 128
11
9 9 162
12
Just to illustrate: 2 * 7^2 = 98 etc
I appreciate any help.
Advertisement
Answer
In your case do
JavaScript
1
14
14
1
df['y'] = df.y.fillna(df.x**2*2)
2
3
0 1.1
4
1 3.9
5
2 11.2
6
3 21.5
7
4 34.8
8
5 51.0
9
6 70.2
10
7 98.0
11
8 128.0
12
9 162.0
13
Name: y, dtype: float64
14