首页 > 解决方案 > python:在Numpy数组数组中的每个数组末尾填充零

问题描述

我有一个 Numpy 数组数组,主数组中的每个数组都有不同的大小。我需要在每个数组的末尾用 0 填充,以便主数组内的所有数组长度相等,但我不知道最大长度。我希望它以更简洁的方式完成,而不是在需要时找到最大长度并在末尾分配 0。下面的a已经是一个Numpy aray

a=[
   [1,2,3,4],
   [3,56],
   [8,4,8,4,9,33,55]
  ] .
   In this case maxlength is 7(the length of third array) . 
   I want final array to look like follows 
a=[
   [1,2,3,4,0,0,0],
   [3,56,0,0,0,0,0],
   [8,4,8,4,9,33,55]
  ]

标签: pythonarraysnumpy

解决方案


对于 numpy.pad 解决方案,我认为我们需要确保您的输入与您的输入完全一致,以便我们能够获得正确的解决方案。那么它将是:

a=[
      np.asarray([1,2,3,4]),
      np.asarray([3,56]),
      np.asarray([8,4,8,4,9,33,55])
 ]


max_len = max([len(x) for x in a])

output = [np.pad(x, (0, max_len - len(x)), 'constant') for x in a]

print(output)

>>> [
     array([1, 2, 3, 4, 0, 0, 0]), 
     array([ 3, 56,  0,  0,  0,  0,  0]), 
     array([ 8,  4,  8,  4,  9, 33, 55])
    ]

推荐阅读