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

标签 python arrays numpy matrix

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

P.S: I don't want to use python loop!

> 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]]

My for loop approach:

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]]

最佳答案

鉴于示例数据中的每一行长度不等,您可以使用 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)

关于python - 使用 numpy 将矩阵元素替换为其他矩阵元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60215898/

相关文章:

python - 如何在没有pip的情况下安装python模块?

php - 在 PHP 中将数组的递增索引值插入数据库时​​出错

python 2 定时器不遵循顺序

c - 将数组写入文本文件

python - python中的线平滑算法?

python - SciPy 1D 高斯拟合

python - 如何在 xlsxwriter 中使用条件格式()的行列表示法

模块级别的 Python 列表

python - 从 FTP 检索文件时如何指定本地目标文件夹

c++ - 如何将 vector 转换为数组