Home > Software design >  How to replace ffill() method with custom function in pandas
How to replace ffill() method with custom function in pandas

Time:07-18

here is my sample df:

    x   y
0   0   1.1
1   1   3.9
2   2   11.2
3   3   21.5
4   4   34.8
5   5   51.0
6   6   70.2
7   7   NaN
8   8   NaN
9   9   NaN

If I would like to replace the NaN values and ffill the last number (70.2 - in this case), I would simply apply:

df['y'].ffill(inplace=True)

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:

    x   y
0   0   1.1
1   1   3.9
2   2   11.2
3   3   21.5
4   4   34.8
5   5   51.0
6   6   70.2
7   7   98
8   8   128
9   9   162 

Just to illustrate: 2 * 7^2 = 98 etc

I appreciate any help.

CodePudding user response:

In your case do

df['y'] = df.y.fillna(df.x**2*2)

0      1.1
1      3.9
2     11.2
3     21.5
4     34.8
5     51.0
6     70.2
7     98.0
8    128.0
9    162.0
Name: y, dtype: float64
  • Related