python - 使用 numpy 将矩阵元素替换为其他矩阵元素
问题描述
我正在尝试zero_matrix
用元素替换 的所有元素,x
但不确定要使用哪个确切的 numpy 函数!
PS:我不想用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]]
解决方案
鉴于样本数据中的每一行长度不等,您可以使用它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)
推荐阅读
- vb.net - 如何使用 vb.net 从 Dropbox 文件夹中复制 Dropbox 文件链接
- c# - 如何仅将对话列表放在它自己的滚动视图中?
- python - 在 python 中,我想要数千个单独的十进制数字并以 2 个十进制数字显示
- sylius - 如何在 Sylius 中自定义 Stripe 模板?
- azure - Azure 中的人脸检测
- java - MVC:下拉菜单中的值未设置为选定值 - 保持为 0
- javascript - JavaScript 类是否有与 Python 类的 __call__ 等效的方法?
- javascript - 在带有空格的对象内搜索字符串名称
- html - 使用带有标签的 react-router 链接
- sql - 按顺序更新列值,其中新值基于“上一个”行中的更新值