Fill na values by adding x to previous row pandas

后端 未结 1 1725
死守一世寂寞
死守一世寂寞 2021-01-18 12:59

I have a data frame with a column named SAM with following data

SAM
3
5
9
Nan
Nan
24
40
Nan
57

Now I want to Insert 12,

1条回答
  •  不知归路
    2021-01-18 13:58

    You can try this vectorized approach:

    nul = df['SAM'].isnull()
    nul.groupby((nul.diff() == 1).cumsum()).cumsum()*3 + df['SAM'].ffill()
    
    #0     3.0
    #1     5.0
    #2     9.0
    #3    12.0
    #4    15.0
    #5    24.0
    #6    40.0
    #7    43.0
    #8    57.0
    #Name: SAM, dtype: float64
    
    1. Divide the missing values in the series into chunks and add 3,6,9 etc to the missing value positions depending on the length of each chunk;
    2. Add the forward filled values from SAM column to the result.

    0 讨论(0)
提交回复
热议问题