2016-04-28 66 views
0

在大熊貓時間序列可以說我有這個數據彙總給出的窗口大小

a = pandas.Series([1,2,3,4,5,6,7,8]) 

a 
Out[313]: 
0 1 
1 2 
2 3 
3 4 
4 5 
5 6 
6 7 
7 8 
dtype: int64 

我想總該數據組的數據在時間n行,總結起來。因此,如果n=2新系列看起來像{3,7,11,15}

+0

你的意思是{3,7,11,15}?另外如果有奇數的元素呢?你打算如何添加它們? – Kevad

回答

1

試試這個:

In [39]: a.groupby(a.index//2).sum() 
Out[39]: 
0  3 
1  7 
2 11 
3 15 
dtype: int64 

In [41]: a.index//2 
Out[41]: Int64Index([0, 0, 1, 1, 2, 2, 3, 3], dtype='int64') 

N = 3

In [42]: n=3 

In [43]: a.groupby(a.index//n).sum() 
Out[43]: 
0  6 
1 15 
2 15 
dtype: int64 

In [44]: a.index//n 
Out[44]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2], dtype='int64') 
0

可以使用熊貓rolling mean並得到它像下面這樣: 如果n是您的間隔時間:

sums = list(a.rolling(n).sum()[n-1::n]) 

# Optional !!! 
rem = len(a)%n 
if rem != 0: 
    sums.append(a[-rem:].sum()) 

如果數據可以正確,第一行將完美添加行我們也可以添加剩餘的金額(取決於您的偏好)。 例如,在上述情況下,如果n=3,那麼您可能想要得到{6, 15, 15}或只是{6, 15}。上面的代碼是針對前一種情況。並跳過可選部分只給你{6, 15}