我正在尝试将 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/