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

Pandas foward fill in between – same values

I am trying to do the following:

Supposing I have the following column on pandas, where there will be always two values that are equal in sequence.

l = [np.nan, np.nan, 10, np.nan, np.nan, np.nan, 10, np.nan, 4, np.nan, 4, 5, np.nan, 5, np.nan,  2, np.nan, 2, 1, 1]

How can I fill NaN values only in between the interval of similar values ?

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

expected output:

[np.nan, np.nan, 10, 10, 10, 10, 10, np.nan, 4, 4, 4, 5, 5, 5, np.nan,  2, 2, 2, 1, 1]

I could only find this answer, which is not the same problem:

Stackoverflow Question

>Solution :

Solution with ffill and bfill

f = df['col'].ffill()
b = df['col'].bfill()

df['col'].mask(f == b, f)

0      NaN
1      NaN
2     10.0
3     10.0
4     10.0
5     10.0
6     10.0
7      NaN
8      4.0
9      4.0
10     4.0
11     5.0
12     5.0
13     5.0
14     NaN
15     2.0
16     2.0
17     2.0
18     1.0
19     1.0
Name: col, 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