有没有办法在 python 中的 numpy 数组中的每一行添加不同的数字?

Is there a way to add a different number to each row in a numpy array in python?

我想为下面矩阵的每一行添加一个不同的数字。

array([[  6,   6,   6,   6],
       [  1,  -5, -11, -17],
       [  1,   7,  13,  19]], dtype=int64)

例如我想将这个数组添加到矩阵中:

array([-4, -3,  0])

将数组的 -4 添加到第一行,因此它将是 array([2, 2, 2, 2], dtype=int64)

整个矩阵应该如下所示:

array([[  2,   2,   2,   2],
       [ -2,  -8, -14, -20],
       [  1,   7,  13,  19]], dtype=int64)

我当然可以将一维数组转换为矩阵,但我想知道是否还有其他选择。

您可以通过多种方式完成:

  1. 使用.reshape:它将创建一个“列向量”而不是“行向量”
a + b.reshape((-1,1))
  1. 正在创建一个新数组然后转置它:
a + np.array([b]).T
  1. 使用numpy.atleast_2d:
a + np.atleast_2d(b).T

它们都具有相同的输出:

array([[  2,   2,   2,   2],
       [ -2,  -8, -14, -20],
       [  1,   7,  13,  19]])

性能

%%timeit 
a = np.random.randint(0,10,(2000,100)) 
b = np.random.randint(0,10,2000) 
a + b.reshape((-1,1)) 
#3.39 ms ± 43.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit 
a = np.random.randint(0,10,(2000,100)) 
b = np.random.randint(0,10,2000) 
a + np.array([b]).T
#3.4 ms ± 81.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit 
a = np.random.randint(0,10,(2000,100))
b = np.random.randint(0,10,2000)
a + np.atleast_2d(b).T
#3.37 ms ± 58.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)