Home > Mobile >  Sum of last values of a dataframe column
Sum of last values of a dataframe column

Time:06-09

I would like to create a new column where the values are the sum of the last 14 values of column atr1, How can I do it?

I tried

col = a.columns.get_loc('atr1')
a['atrsum'] = a.iloc[-14:,col].sum()

But I get only a fixed value in the new column. Dataframe below as reference.

   time             open    high    low     close   volume          atr1
0   1620518400000   1.6206  1.8330  1.5726  1.7663  8.830913e 08    NaN
1   1620604800000   1.7662  1.8243  1.5170  1.6423  7.123049e 08    0.3073
2   1620691200000   1.6418  1.7791  1.5954  1.7632  5.243267e 08    0.1837
3   1620777600000   1.7633  1.8210  1.5462  1.5694  5.997101e 08    0.2748
4   1620864000000   1.5669  1.9719  1.5000  1.9296  1.567655e 09    0.4719
... ... ... ... ... ... ... ...
360 1651622400000   0.7712  0.8992  0.7677  0.8985  2.566498e 08    0.1315
361 1651708800000   0.8986  0.9058  0.7716  0.7884  3.649706e 08    0.1342
362 1651795200000   0.7884  0.7997  0.7625  0.7832  2.440587e 08    0.0372
363 1651881600000   0.7832  0.7858  0.7467  0.7604  1.268089e 08    0.0391
364 1651968000000   0.7605  0.7663  0.7254  0.7403  1.751395e 08    0.0409

CodePudding user response:

use expanding function of pandas

14 is the number of days, followed by the column you like to sum

a.expanding(14)['atr1'].sum()

I must be missing something in the question, ,my apologies. I just used the data you shared and used the 2 previous days and this is the result

df['atrsum'] = df['atr1'].expanding(2).sum()
    id       time          open     high    low     close   volume         atr1     atrsum
0   0        1620518400000  1.6206  1.8330  1.5726  1.7663  8.830913e 08    NaN     NaN
1   1        1620604800000  1.7662  1.8243  1.5170  1.6423  7.123049e 08    0.3073  NaN
2   2        1620691200000  1.6418  1.7791  1.5954  1.7632  5.243267e 08    0.1837  0.4910
3   3        1620777600000  1.7633  1.8210  1.5462  1.5694  5.997101e 08    0.2748  0.7658
4   4        1620864000000  1.5669  1.9719  1.5000  1.9296  1.567655e 09    0.4719  1.2377
5   360     1651622400000   0.7712  0.8992  0.7677  0.8985  2.566498e 08    0.1315  1.3692
6   361     1651708800000   0.8986  0.9058  0.7716  0.7884  3.649706e 08    0.1342  1.5034
7   362     1651795200000   0.7884  0.7997  0.7625  0.7832  2.440587e 08    0.0372  1.5406
8   363     1651881600000   0.7832  0.7858  0.7467  0.7604  1.268089e 08    0.0391  1.5797
9   364     1651968000000   0.7605  0.7663  0.7254  0.7403  1.751395e 08    0.0409  1.6206

CodePudding user response:

At least for me the answer from Naveed did not work, but I found a different way:

a['atrsum']= a['atr1'].rolling(window=14).apply(sum).dropna()

This gives me the result.

  • Related