使用滚动窗口从数据框创建“缓冲区”矩阵?

时间:2016-08-19 14:38:29

标签: python pandas numpy dataframe

鉴于只有一列的数据帧,如何将其转换为另一个数据帧“缓冲区”(大小为2),如下所述:

df =

   0
0  1
1  2
2  3
3  4
4  4
5  5
6  5

expected_buffer =

   0 1
0  1 2
1  2 3
2  3 4 
3  4 5

这是我的尝试:

def buff(df,past):
    arr1=df.values
    arr=arr1[0:past]
    for i in xrange(past,df.shape[0]-past+2):
        arr=np.append(arr,arr1[i:past+i],axis=0)
    return pd.DataFrame(arr)

返回以下内容:

   0
0  1
1  2
2  3
3  4
4  4
5  5
6  5

如何获得预期的buff输出?

编辑: past我的意思是缓冲区大小。使用MATLAB表示法:我有5个元素列向量

df = [1;2;3;4;5]

如果past为2,我最终会得到以下输出:

buff = [1 2; 2 3; 3 4; 4 5]

如果past为3,则预期输出应为

buff = [1 2 3; 2 3 4; 3 4 5]

如果past为4,则预期输出为

buff = [1 2 3 4; 2 3 4 5]

因此对于n - 元素dfpast=m,我会得到一个大小为(n-past+1) x past的矩阵。

2 个答案:

答案 0 :(得分:3)

def buff(df, past):
    a = np.concatenate([df.values[i:i-past] for i in range(past)], axis=1)
    return pd.DataFrame(a, columns=list(range(past)))
buff(df, 2)

enter image description here

buff(df, 3)

enter image description here

buff(df, 4)

enter image description here

buff(df, 5)

enter image description here

答案 1 :(得分:3)

import pandas as pd

def buff(s, n):
    return (pd.concat([s.shift(-i) for i in range(n)], axis=1)
              .dropna().astype(int))

s = pd.Series([1,2,3,4,5])
print(buff(s, 2))

#    0  0
# 0  1  2
# 1  2  3
# 2  3  4
# 3  4  5

print(buff(s, 3))

#    0  0  0
# 0  1  2  3
# 1  2  3  4
# 2  3  4  5

print(buff(s, 4))

#    0  0  0  0
# 0  1  2  3  4
# 1  2  3  4  5