python - 使用滚动窗口从数据帧创建 "buffer"矩阵?

标签 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过去

最佳答案

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

关于python - 使用滚动窗口从数据帧创建 "buffer"矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39041769/

相关文章:

python - Pyramid debug_toolbar : disabled perfomance tab with Python 2. 6,但启用了 python 3.2

python - 将平面列表转换为二元组

python - 将 Pandas 值组合到成员组中

python - 生成没有重复列的位向量数组

python - 检查二维 numpy 数组中的 nan

python - 如何在 flask 上存储我自己的变量

python - 删除用作 dict 中 key 的对象不会删除 dict 中对应的 key

python - 在 Python Pandas 中,搜索值上升的连续 4 行

python - 给定另一个数据帧中两列的值约束,查找一个数据帧的一列中的最大值

python - 求解具有 4 个未知数的大型方程组