Create a new column that is the sum of the previous three values in the pandas data frame

Asked 2 years ago, Updated 2 years ago, 40 views

Calculate the top three cumulative values from data in DF format

 Data Result expression
A   1          0    
B   2          0    
C   3          0    
D   4          6    A+B+C
E   5          9    B+C+D
F   6          12   C+D+E
G   7          15   D+E+F
H   8          18   E+F+G
I   9          21   F+G+H

As above, I want to make the accumulated value of the top three column values based on the data into Pandas, so what should I do?

python pandas

2022-09-20 08:57

2 Answers

>>> import pandas as pd
>>> df = pd.DataFrame({ "Data":range(1, 10) }, index=list("ABCDEFGHI"))
>>> df
   Data
A     1
B     2
C     3
D     4
E     5
F     6
G     7
H     8
I     9

>>> i = 4
>>> df.iloc[(i-3):i, 0]
B    2
C    3
D    4
Name: Data, dtype: int64

>>> s = [ sum(df.iloc[(i-3):i, 0]) for i in range(3, len(df)) ]
>>> s
[6, 9, 12, 15, 18, 21]
>>> s = [ 0, 0, 0 ] + s
>>> s
[0, 0, 0, 6, 9, 12, 15, 18, 21]

>>> df["Result"] = s
>>> df
   Data  Result
A     1       0
B     2       0
C     3       0
D     4       6
E     5       9
F     6      12
G     7      15
H     8      18
I     9      21


2022-09-20 08:57

Thank you every time.


2022-09-20 08:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.