Pad list of arrays with zeros in order all arrays to have the same size

Viewed 463

I have created this array(or I think its a list) that consist of many arrays that are different size and that is the reason I put dtype = object .

m = [data[a:b] for a, b in zip(z[0:-1:2], z[1:-1:2])]


array = np.array(m, dtype=object)

I need to pad each array with zero so that they have the same size (lets say size=smax) and become a "proper" array. My definitions are a little off and I am sorry in advance

1 Answers

You can do this using np.pad on each row. For example:

import numpy as np
data = np.arange(10)
z = [0, 2, 1, 4, 6, 10, 8, 9]
m = [data[a:b] for a, b in zip(z[0:-1:2], z[1:-1:2])]

max_length = max(len(row) for row in m)
result = np.array([np.pad(row, (0, max_length-len(row))) for row in m])

print(result)
# [[0 1 0 0]
#  [1 2 3 0]
#  [6 7 8 9]]
Related