没有循环的固定数量的元素的Cumsum

时间:2017-03-06 21:56:37

标签: python pandas numpy cumsum

我有Python,它从列中开始计算14个元素的cumsum,从不同的元素开始,并将此总和写入其他列。有没有人知道没有循环怎么做?

import pandas as pd
import numpy as np

a = pd.DataFrame({"A": [i for i in range(25)]})
b = pd.DataFrame({"B": [np.nan for i in range(25)]})
for i in range(4, len(b)):
    cumsum = 0
    for k in range(i - 4, i):
        cumsum += a.A[k]
    b.B[k] = cumsum
pd.concat([a,b], axis=1)

1 个答案:

答案 0 :(得分:3)

IIUC您正在寻找rolling(4) + _traceService.Trace("This message is not logged"); try { using (var sr = new StreamReader(request.GetResponse().GetResponseStream())) using (var jsonTextReader = new JsonTextReader(sr)) { _traceService.Trace("Success"); _traceService.Trace(jsonTextReader.ToString()); var ret = serializer.Deserialize<T>(jsonTextReader); sw.Stop(); _traceService.Trace("MadeRequest {0}", sw.Elapsed); return ret; } } catch (WebException e) { using (var sr = new StreamReader(e.Response.GetResponseStream())) using (var jsonTextReader = new JsonTextReader(sr)) { _traceService.Trace("Error"); _traceService.Trace("Error: " + e.Message); throw; } }

sum()

检查:

In [83]: a['new'] = a.A.rolling(4).sum()

In [84]: a
Out[84]:
     A   new
0    0   NaN
1    1   NaN
2    2   NaN
3    3   6.0
4    4  10.0
5    5  14.0
6    6  18.0
7    7  22.0
8    8  26.0
9    9  30.0
10  10  34.0
11  11  38.0
12  12  42.0
13  13  46.0
14  14  50.0
15  15  54.0
16  16  58.0
17  17  62.0
18  18  66.0
19  19  70.0
20  20  74.0
21  21  78.0
22  22  82.0
23  23  86.0
24  24  90.0