需要有效的方法将较小的 Numpy 数组广播到较大的数组中

Need efficient method to broadcast a smaller Numpy array into a larger one

TL;DR:我正在寻找一种不使用循环来缩短以下代码的方法

# x = [m, n] Numpy array
# y = [m, t*n] Numpy array of zeros (placeholder)
for i in range(m):
    for j in range(n):
        y[i, t*j:t*(j+1)] = x[i, j]

更多解释:我想做的是 copy/broadcast 一个二维数组变成一个更大的数组,在第二个维度中重复元素 t 次。上面的代码工作正常,但我想通过避免使用循环来保持它的效率。

np.repeat(x,n,axis=1)

这将在没有任何零数组初始化的情况下工作!假设您只想重复列中的前一个数组。

如果我要使用 numpy 复制您的函数,我会这样做:

import numpy as np

a = np.arange(float(m * n)).reshape(m, n)

def expand_array(a, t):
    m, n = a.shape
    return np.repeat(a[:, -1], t * n).reshape(m, t * n)

def op_func(a, t):
    m, n = a.shape
    y = np.zeros((m, n * t))
    for i in range(m):
        for j in range(n):
            y[i, :] = x[i, j]

    return y

(expand_array(a, 10) == op_func(a, 10)).all()

输出:

True

但是,正如我在评论中指出的那样,这实际上跳过了除最后一列以外的每一列。因此,我怀疑您想要更像是以下两者之一的东西:

def repeat_expand_array(a, t):
    m, n = a.shape
    return np.repeat(a, t).reshape(m, t * n)

def tile_expand_array(a, t):
    m, n = a.shape
    return np.tile(a, t).reshape(m, t * n)

print(repeat_expand_array(a, 3), '\n')
print(tile_expand_array(a, 3))

输出:

[[0. 0. 0. 1. 1. 1.]
 [2. 2. 2. 3. 3. 3.]
 [4. 4. 4. 5. 5. 5.]] 

[[0. 1. 0. 1. 0. 1.]
 [2. 3. 2. 3. 2. 3.]
 [4. 5. 4. 5. 4. 5.]]