基于其他阵列形状的零垫阵列 [英] Zero pad array based on other array's shape

查看:105
本文介绍了基于其他阵列形状的零垫阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有K个特征向量,它们全部共享维n,但具有可变维m(n x m).他们都一起生活在一个清单中.

I've got K feature vectors that all share dimension n but have a variable dimension m (n x m). They all live in a list together.

to_be_padded = []

to_be_padded.append(np.reshape(np.arange(9),(3,3)))

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

to_be_padded.append(np.reshape(np.arange(18),(3,6)))

array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

to_be_padded.append(np.reshape(np.arange(15),(3,5)))

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

我正在寻找的是一种聪明的方法,以零填充这些np.arrays的行,以使它们都共享相同的维m.我曾尝试使用np.pad解决它,但我还无法提出一个漂亮的解决方案.在正确方向上的任何帮助或推动将不胜感激!

What I am looking for is a smart way to zero pad the rows of these np.arrays such that they all share the same dimension m. I've tried solving it with np.pad but I have not been able to come up with a pretty solution. Any help or nudges in the right direction would be greatly appreciated!

结果应使数组看起来像这样:

The result should leave the arrays looking like this:

array([[0, 1, 2, 0, 0, 0],
       [3, 4, 5, 0, 0, 0],
       [6, 7, 8, 0, 0, 0]])

array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

array([[ 0,  1,  2,  3,  4, 0],
       [ 5,  6,  7,  8,  9, 0],
       [10, 11, 12, 13, 14, 0]])

推荐答案

您可以使用

You could use np.pad for that, which can also pad 2-D arrays using a tuple of values specifying the padding width, ((top, bottom), (left, right)). For that you could define:

def pad_to_length(x, m):
    return np.pad(x,((0, 0), (0, m - x.shape[1])), mode = 'constant')

使用情况

您可以从查找列数最多的ndarray开始.假设您有两个ab:

You could start by finding the ndarray with the highest amount of columns. Say you have two of them, a and b:

a = np.array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

b = np.array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

m = max(i.shape[1] for i in [a,b])
# 5

然后使用此参数填充ndarrays:

pad_to_length(a, m)
array([[0, 1, 2, 0, 0],
       [3, 4, 5, 0, 0],
       [6, 7, 8, 0, 0]])

这篇关于基于其他阵列形状的零垫阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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