【问题标题】:creating an numpy matrix with a lag创建一个滞后的 numpy 矩阵
【发布时间】:2014-02-09 08:34:33
【问题描述】:

假设我有

q=2

y=[5,10,5,15,20,25,30,35,5,10,15,20]

n=len(y)

我想制作一个具有 nxq 维度的矩阵,其中第一行是 [5,10],第二行是 [10,5],第三行是 [5,15] ...等等.

有没有办法做到这一点,或者我必须使用for loopconcatenate 函数?

【问题讨论】:

    标签: numpy matrix iteration


    【解决方案1】:

    我们的好朋友 index_tricks 来救援:

    import numpy as np
    
    #illustrate functionality on a 2d array
    y=np.array([5,10,5,15,20,25,30,35,5,10,15,20]).reshape(2,-1)
    
    def running_view(arr, window, axis=-1):
        """
        return a running view of length 'window' over 'axis'
        the returned array has an extra last dimension, which spans the window
        """
        shape = list(arr.shape)
        shape[axis] -= (window-1)
        assert(shape[axis]>0)
        return np.lib.index_tricks.as_strided(
            arr,
            shape + [window],
            arr.strides + (arr.strides[axis],))
    
    print running_view(y, 2)
    

    它将视图返回到原始数组中,因此性能为 O(1)。 编辑:概括为包含 nd 数组的可选轴参数。

    【讨论】:

    • 你完全明白了。现在我必须查看index_tricks 并尝试了解发生了什么
    • 更新后的代码使逻辑更加明确。 as_strided 允许您覆盖数组步幅(谨慎使用;它也允许您创建越界步幅)。 arr.strides + (arr.strides[axis],) 告诉 numpy 沿窗口轴的步长与沿要查看的轴的步长相同;很简单。这只留下一些逻辑来产生一个不允许越界索引的正确形状。
    • 我不确定你的意思;我确实插入了一个新维度,它确实具有“任意”和正确的步幅。啊,我想你是在回复我的预编辑帖子。
    • 是的,第一次重塑可能应该被删除,这让我很困惑。
    • 第一次重塑只是为了说明该函数不仅仅适用于一维数组
    【解决方案2】:

    由于 NumPy 数组默认为row-major ordered,您可以直接reshape() 将数组“包裹”到矩阵的行中(假设列数除以数组的长度)。

    import numpy as np
    
    def as_matrix(x, ncols):
        nrows = len(x) // ncols
        return np.array(x).reshape(nrows, ncols)
    
    as_matrix(y, 2)
    
    #> array([[ 5, 10],
    #>        [ 5, 15],
    #>        [20, 25],
    #>        [30, 35],
    #>        [ 5, 10],
    #>        [15, 20]])
    

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 2017-06-18
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2017-04-12
      • 2022-11-02
      相关资源
      最近更新 更多