0

I have a list of numpy arrays like this (any size):

a = [array(2,3,4), array(2,3), array(2)]

How can I with a minimal number of lines of code create a padded matrix, with padding symbol "0" like this:

array([[2, 3, 4],
       [2, 3, 0],
       [2, 0, 0]
])
user1506145
  • 4,996
  • 8
  • 40
  • 70

1 Answers1

1

One option is to use zip_longest from itertools, and you can fill values of zero for the shorter array until they have the same length as the longest array:

from itertools import zip_longest
from numpy import array

a = [array([2,3,4]), array([2,3]), array([2])]

array(list(zip(*zip_longest(*a, fillvalue=0))))

#array([[2, 3, 4],
#       [2, 3, 0],
#       [2, 0, 0]])
Psidom
  • 195,464
  • 25
  • 298
  • 322