Search code examples
pythonpandasfillzero

Replace pandas zero value with ffill non-zero, if the subsequent value is non-zero


I need to replace "0" row data in pandas with the previous rows non-zero value IF and ONLY IF, the value in the row following the "0" is non zero.

I.e.

101
92
78
0
107
0
0

would become:

101
92
78
78
107
0
0

Any ideas how to do this would be much appreciated :-)

Thanks!


Solution

  • using shift you could do

    In [608]: df.loc[(df.val == 0) & (df.val.shift(-1) != 0), 'val'] = df.val.shift(1)
    
    In [609]: df
    Out[609]:
         val
    0  101.0
    1   92.0
    2   78.0
    3   78.0
    4  107.0
    5    0.0
    6    0.0