我有 K 个特征向量,它们都共享维度 n 但具有可变维度 m (n x m)。他们都生活在一个列表中。
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 解决它,但我还没有想出一个漂亮的解决方案。任何朝着正确方向的帮助或插入将不胜感激!
结果应该使数组看起来像这样:
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]])
最佳答案
您可以使用 np.pad
为此,它也可以垫 2-D
使用指定填充宽度的值元组的数组,((top, bottom), (left, right))
.为此,您可以定义:
def pad_to_length(x, m):
return np.pad(x,((0, 0), (0, m - x.shape[1])), mode = 'constant')
用法
您可以先找到
ndarray
列数最多。假设你有两个,a
和 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]])
关于python - 基于另一种阵列形状的零焊盘阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54591005/