滑动 window 在列而不是行上向下遍历

sliding window traverses downward on column instead of rows

我正在尝试构建一个滑动 window,它使用下面的代码片段遍历每一行:

从excel读取数据:

import numpy as np
import pandas as pd

data = pd.read_excel('link_to_excel', header=None)
vals = pd.DataFrame.to_numpy(data)
col_count, row_count = vals.shape

来自 excel 的数据如下所示:

i = [[ 1  2  3  4  5  6  7  8  9 10]
     [11 12 13 14 15 16 17 18 19 20]
     [21 22 23 23 25 26 27 28 29 30]
     [ 1  2  3  4  5  6  7  8  9 10]
     [21 22 23 23 25 26 27 28 29 30]
     [21 22 23 23 25 26 27 28 29 30]
     [ 1  2  3  4  5  6  7  8  9 10]]

滑动window函数:

def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides, writeable=False)

当我运行:

window = 6
print(rolling(i, window))

我得到一个看起来像这样的滑动 window(向下遍历 i 上的列):

[[ 1 11 21  1 21 21]
 [11 21  1 21 21  1]
 [21  1 21 21  1  2]
 [ 1 21 21  1  2 12]
 [21 21  1  2 12 22]]

所需的滑动 window 我正在寻找基于 i:

first
[[1 2 3 4 5  6]
 [2 3 4 5 6  7]
 [3 4 5 6 7  8]
 [4 5 6 7 8  9]
 [5 6 7 8 9 10]]

当我使用 np.random.randint(1, 31, size=(7, 10)) 生成 i 时,我得到了我想要的结果。

如何在读取 excel 时获得所需的滑动 window?

print(i.ravel(order='K'))

的输出
[ 1 11 21  1 21 21  1  2 12 22  2 22 22  2  3 13 23  3 23 23  3  4 14 24
  4 24 24  4  5 15 25  5 25 25  5  6 16 26  6 26 26  6  7 17 27  7 27 27
  7  8 18 28  8 28 28  8  9 19 29  9 29 29  9 10 20 30 10 30 30 10]

print(i.shape)

的输出
(7,10)

样本excelsheet

我的 pandas 上没有安装 xlrd 支持,但正在将其导出到 csv:

In [168]: data = pd.read_csv('../Downloads/Untitled spreadsheet - Sheet1.csv', h
     ...: eader=None)
In [169]: data
Out[169]: 
    0   1   2   3   4   5   6   7   8   9
0   1   2   3   4   5   6   7   8   9  10
1  11  12  13  14  15  16  17  18  19  20
2  21  22  23  24  25  26  27  28  29  30
3   1   2   3   4   5   6   7   8   9  10
4  21  22  23  24  25  26  27  28  29  30
5  21  22  23  24  25  26  27  28  29  30
6   1   2   3   4   5   6   7   8   9  10
In [170]: data = data.values

strides 显示它是 order F, ravel with order 'K'

In [171]: data.strides
Out[171]: (8, 56)
In [172]: data.ravel('K')
Out[172]: 
array([ 1, 11, 21,  1, 21, 21,  1,  2, 12, 22,  2, 22, 22,  2,  3, 13, 23,
        3, 23, 23,  3,  4, 14, 24,...])

In [175]: data.ravel('C')
Out[175]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22,...])

In [177]: rolling(data.ravel('C'),6)
Out[177]: 
array([[ 1,  2,  3,  4,  5,  6],
       [ 2,  3,  4,  5,  6,  7],
       [ 3,  4,  5,  6,  7,  8],
       [ 4,  5,  6,  7,  8,  9],
       [ 5,  6,  7,  8,  9, 10],
       ...

我还没有看到之前讨论过的 order 数据帧值。但是由于 DataFrame 是一系列列的集合,因此 2d 数组版本将按 'F' 顺序排列是有意义的,值会沿着列向下排列。

您想 roll 跨列,因此您需要更改数组的顺序。