在python中扩展不同的形状/尺寸矩阵 [英] Extend different shapes/dimension matrices in python

查看:81
本文介绍了在python中扩展不同的形状/尺寸矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用零使两个矩阵具有相同的尺寸/形状填充.

I want to make two matrices same dimension/shape padding with zeros..

例如我有

>>> x
array([[ 1.,  -1.,  1.],
       [ 1.,  1., - 1.]])
>>> 
>>> 
>>> y
array([[ 2.,  2.],
       [ 2.,  2.],
       [ -2.,  2.]])

我想要的输出

x1 = array([[ 1.,  -1.,  1.],
           [ 1.,  1.,  -1.],
           [ 0.,  0.,  0.]])

y1 =array([[ 2.,  2., 0.],
           [ 2.,  2., 0.],
           [ -2.,  2., 0.]])

有什么帮助吗?我查找了"pad",但我们使用的numpy版本较旧,因此没有pad. (numpy版本1.6.x)

any help? I looked up the "pad" but the numpy version we are using is older so it does not have pad. ( numpy ver. 1.6.x)

我还查看了一些解决方案,但是它们特定于形状,在我的情况下,形状是动态的-并且操作需要快速-因为我在大型矩阵上执行了很多次

I also looked up some solutions but they are specific to shape, in my case the shape is dynamic -- and the operation needs to be fast -- as I do this over a large matrices and many times

推荐答案

每个数组都有一个shape:

>>> x = np.array([[ 1.,  -1.,  1.],
...               [ 1.,  1., - 1.]])
>>> y = np.array([[ 2.,  2.],
...               [ 2.,  2.],
...               [ -2.,  2.]])
>>> x.shape
(2, 3)
>>> y.shape
(3, 2)

我们只需要计算最大形状"并将其用于新数组:

We just need to compute the "maximum shape" and use that for the new arrays:

>>> shape = np.maximum(x.shape, y.shape)
>>> x1 = np.zeros(shape)

然后我们可以将数据从原始数组复制到新数组的相应部分:

We can then copy the data from the original arrays into the corresponding parts of the new arrays:

>>> x1[:x.shape[0], :x.shape[1]] = x
>>> y1 = np.zeros(shape)
>>> y1[:y.shape[0], :y.shape[1]] = y

结果

>>> x1
array([[ 1., -1.,  1.],
       [ 1.,  1., -1.],
       [ 0.,  0.,  0.]])
>>> y1
array([[ 2.,  2.,  0.],
       [ 2.,  2.,  0.],
       [-2.,  2.,  0.]])
>>>

这篇关于在python中扩展不同的形状/尺寸矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆