使用numpy将矩阵元素替换为其他矩阵元素

时间:2020-02-13 20:24:08

标签: python arrays numpy matrix

我正在尝试将zero_matrix的所有元素替换为x的元素,但不确定要使用哪个确切的numpy函数!

P.S:我不想使用python循环!

> zero_matrix = np.zeros((5, 15), dtype=np.int32)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)

> x = [[3822, 510, 4, 1, 20672],
 [3822, 510, 4, 1, 20672, 3822, 510, 4, 1, 20672],
 [3822, 3822, 510, 4, 1, 20672],
 [3822, 510, 510, 4, 1, 20672],
 [3822, 510, 4, 1, 20672, 4, 1, 20672]]

我的for循环方法:

for i in range(len(x)):
    zero_matrix[i][:len(x[i])] = x[i]

[[ 3822   510     4     1 20672     0     0     0     0     0     0     0
      0     0     0]
 [ 3822   510     4     1 20672  3822   510     4     1 20672     0     0
      0     0     0]
 [ 3822  3822   510     4     1 20672     0     0     0     0     0     0
      0     0     0]
 [ 3822   510   510     4     1 20672     0     0     0     0     0     0
      0     0     0]
 [ 3822   510     4     1 20672     4     1 20672     0     0     0     0
      0     0     0]]

1 个答案:

答案 0 :(得分:2)

鉴于示例数据中的每一行的长度均不相等,可以使用zip_longest来制作一个填充有零的正方形数组。请注意,需要对数组进行转置以使其恢复到预期的形状。然后只需将结果分配到zero_matrix中的等效位置即可。

from itertools import zip_longest

a = np.array(list(zip_longest(*x, fillvalue=0))).T
rows, cols = a.shape
zero_matrix[:rows, :cols] = a

>>> zero_matrix
array([[ 3822,   510,     4,     1, 20672,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0],
       [ 3822,   510,     4,     1, 20672,  3822,   510,     4,     1,
        20672,     0,     0,     0,     0,     0],
       [ 3822,  3822,   510,     4,     1, 20672,     0,     0,     0,
            0,     0,     0,     0,     0,     0],
       [ 3822,   510,   510,     4,     1, 20672,     0,     0,     0,
            0,     0,     0,     0,     0,     0],
       [ 3822,   510,     4,     1, 20672,     4,     1, 20672,     0,
            0,     0,     0,     0,     0,     0]], dtype=int32)