将前n行作为列添加到NumPy数组中

时间:2016-07-26 16:16:28

标签: python arrays numpy

我想将以前的n行添加为NumPy数组的列。

例如,如果n=2,则下面的数组......

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

......应该变成以下一个:

[[ 1, 2, 0, 0, 0, 0]
 [ 3, 4, 1, 2, 0, 0]
 [ 5, 6, 3, 4, 1, 2]
 [ 7, 8, 5, 6, 3, 4]
 [ 9, 10, 7, 8, 5, 6]
 [11, 12, 9, 10, 7, 8]]

如果没有在for循环中遍历整个数组,我怎么能做到这一点?

2 个答案:

答案 0 :(得分:4)

这是一种矢量化方法 -

def vectorized_app(a,n):   
    M,N = a.shape
    idx = np.arange(a.shape[0])[:,None] - np.arange(n+1)
    out = a[idx.ravel(),:].reshape(-1,N*(n+1))
    out[N*(np.arange(1,M+1))[:,None] <= np.arange(N*(n+1))] = 0
    return out

示例运行 -

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

In [256]: vectorized_app(a,3)
Out[256]: 
array([[ 1,  2,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 4,  5,  6,  1,  2,  3,  0,  0,  0,  0,  0,  0],
       [ 7,  8,  9,  4,  5,  6,  1,  2,  3,  0,  0,  0],
       [10, 11, 12,  7,  8,  9,  4,  5,  6,  1,  2,  3],
       [13, 14, 15, 10, 11, 12,  7,  8,  9,  4,  5,  6],
       [16, 17, 18, 13, 14, 15, 10, 11, 12,  7,  8,  9]])

运行时测试 -

我正在计时@Psidom's loop-comprehension based method以及此帖中列出的向量化方法,该问题在问题中发布的样本的100x放大版本(就大小而言)中列出:

In [246]: a = np.random.randint(0,9,(600,200))

In [247]: n = 200

In [248]: %timeit np.column_stack(mypad(a, i) for i in range(n + 1))
1 loops, best of 3: 748 ms per loop

In [249]: %timeit vectorized_app(a,n)
1 loops, best of 3: 224 ms per loop

答案 1 :(得分:1)

这是一种在数组开头填充0然后列堆栈的方法:

import numpy as np
n = 2
def mypad(myArr, n):
    if n == 0:
        return myArr
    else:
        return np.pad(myArr, ((n,0), (0,0)), mode = "constant")[:-n]

np.column_stack(mypad(arr, i) for i in range(n + 1))

# array([[ 1,  2,  0,  0,  0,  0],
#        [ 3,  4,  1,  2,  0,  0],
#        [ 5,  6,  3,  4,  1,  2],
#        [ 7,  8,  5,  6,  3,  4],
#        [ 9, 10,  7,  8,  5,  6],
#        [11, 12,  9, 10,  7,  8]])