python - 从二维 numpy 数组创建数据历史记录?

标签 python arrays numpy

假设我有一个形状为 n X m 的二维 numpy 数组(其中 n 是大数且 m >=1 )。每一列代表一个属性。下面提供了 n=5、m=3 的示例:

[[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[13,14,15]]

我想用history_steps = p(1< p <= n) 来训练我的模型的属性历史记录。对于 p=2,我期望的输出(形状为 (n-p+1 X m*p))是

[[1,4,2,5,3,6],
[4,7,5,8,6,9],
[7,10,8,11,9,12],
[10,13,11,14,12,15]]

我尝试通过分隔列然后连接输出来在 pandas 中实现这一点。

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

但是,就我的目的而言,基于 numpy 的方法会更好。另外,我想避免拆分和连接。

我该如何去做呢?

最佳答案

这是一种基于 NumPy 的方法,重点关注使用 np.lib.stride_tricks.as_strided 的性能-

def strided_axis0(a, L = 2):
    # INPUTS :
    # a : Input array
    # L : Length along rows to be cut to create per subarray

    # Store shape and strides info
    m,n = a.shape
    s0,s1 = a.strides
    nrows = m - L + 1

    strided = np.lib.stride_tricks.as_strided

    # Finally use strides to get the 3D array view and then reshape
    return strided(a, shape=(nrows,n,L), strides=(s0,s1,s0)).reshape(nrows,-1)

示例运行 -

In [27]: a
Out[27]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15]])

In [28]: strided_axis0(a, L=2)
Out[28]: 
array([[ 1,  4,  2,  5,  3,  6],
       [ 4,  7,  5,  8,  6,  9],
       [ 7, 10,  8, 11,  9, 12],
       [10, 13, 11, 14, 12, 15]])

关于python - 从二维 numpy 数组创建数据历史记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43197039/

相关文章:

python - PyCharm 3.4.1 : Unresolved reference 'map'

python - 在扭曲中使用线程

python - 创建一个随机类的实例

c# - 将字符串数组转换为 double 组

javascript - 通过给定键从键,值对象中查找值

java - 在java中使用比率方式合并两个数组

python - 在Python中一起打印多个表

python - 这是什么错误? linux 下的 python 脚本

python - Opencv:TypeError:轮廓不是numpy数组,也不是标量

python - numpy: "array_like"对象的正式定义?