简体   繁体   中英

pandas.DataFrame.rolling summing the current row value and the next 2 row value based on Id and time index, to the 1st row's value

GOAL

I want to sum the current row value and the next 2 row value based on ID and time index to the 1st row value. Time index moves forward with a 3day window while the summed values can only have the same ID

The current incorrect functioning

  • 1st row Value SUMMED VALUE = 1st row Value
  • 2nd row value SUMMED VALUE = 1st row value + 2nd row Value
  • 3rd row Value SUMMED VALUE = 3rd row Value + 2nd row Value + 1st row Value

CODE

gr = current_df.groupby("id").rolling('3D').rolling_sum_3.sum()
final_dataframe = pd.DataFrame(gr)

Output

在此处输入图像描述

Goal is the following

  • A.) 1st row Value SUMMED VALUE = 3rd row Value + 2nd row Value + 1st row Value
  • B.) if there is no 2nd or 3rd row value in this ID and 3 day timeframe just leave this field with a NaN value
  • A.) 2nd row value SUMMED VALUE = 2nd row Value + 3rd row Value + 4th row Value
  • B.) if there is no 3rd or 4th row value in this ID and 3 day timeframe just leave this field with a NaN value
  • etc.

I have tried

  • Reversing the series and then taking a sum using a rolling window of 3.
  • The backwards looking rolling sum will then be a forward looking rolling sum because you reversed the sorting order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM