use*_*006 2 iteration numpy matrix
可以说我有
q=2
y=[5,10,5,15,20,25,30,35,5,10,15,20]
n=len(y)
Run Code Online (Sandbox Code Playgroud)
我想制作一个具有 nxq 维度的矩阵,其中第一行为 [5,10],第二行为 [10,5],第三行为 [5,15] ...等。
有没有办法做到这一点,或者我必须使用for loopandconcatenate函数?
我们的好朋友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)
Run Code Online (Sandbox Code Playgroud)
它返回原始数组的视图,因此性能复杂度为 O(1)。编辑:概括为包含 nd 数组的可选轴参数。
| 归档时间: |
|
| 查看次数: |
3186 次 |
| 最近记录: |