【发布时间】: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 loop 和concatenate 函数?
【问题讨论】:
假设我有
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 loop 和concatenate 函数?
【问题讨论】:
我们的好朋友 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 并尝试了解发生了什么
由于 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]])
【讨论】: