pythonpandasdataframefillnaffill

Pandas ffill on section of DataFrame


I am attempting to forward fill a filtered section of a DataFrame but it is not working the way I hoped.

I have df that look like this:

    Col Col2    
0   1   NaN 
1   NaN NaN 
2   3   string  
3   NaN string  

I want it to look like this:

    Col Col2    
0   1   NaN 
1   NaN NaN 
2   3   string  
3   3   string  

This my current code:

filter = (df["col2"] == "string")
df.loc[filter, "col"].fillna(method="ffill", inplace=True)

But my code does not change the df at all. Any feedback is greatly appreciated


Solution

  • We can use boolean indexing to filter the section of Col where Col2 = 'string' then forward fill and update the values only in that section

    m = df['Col2'].eq('string')
    df.loc[m, 'Col'] = df.loc[m, 'Col'].ffill()
    

       Col    Col2
    0  1.0     NaN
    1  NaN     NaN
    2  3.0  string
    3  3.0  string