Fill in the values ​​by adding x to the previous pandas line

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

SAM 3 5 9 Nan Nan 24 40 Nan 57 

Now I want to insert 12 , 15 and 43 respectively, into the Nan values ​​(because 9+3=12 , 12+3=15 and 40+3=43 ). In other words, fill out any Nan line by adding 3 to the previous line (which could also be Nan ).

I know that this can be done by iterating through a for loop. But can we do this in vector form? Like some modified version of ffill (which could be used here if we didn't have sequential pandas.fillna() ) in pandas.fillna() .

+6
source share
1 answer

You can try this vector 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 
  • Divide the missing values ​​in the series into pieces and add 3,6,9, etc. in the position of missing values ​​depending on the length of each fragment;
  • Add forward values ​​from the SAM column to the result.
+7
source

Source: https://habr.com/ru/post/1013153/


All Articles