Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace ffill() method with custom function in pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading