Reputation: 38157
How do you elegantly create a NumPy ndarray
from (1D-)arrays of different lengths, padding the remainder?
The arrays are always 1D, they have different lengths (maximum length varied between 20 and 100).
Say there is
a = range(40)
b = range(30)
The resultant ndarray
should be
X = [[0,1,2,3,...,39,40],
[0,1,2,...29,30,0,0,...,0]]
Creating an intermediary
I = [a,b]
and padding to a maximum
via
I[1].extend([0] * (maximum - len(I[1])))
which can then be converted via
X = np.array(I)
works but is there nothing built-in / available via PyPI / more pythonic?
Upvotes: 0
Views: 320
Reputation: 69086
You could create an array of zeros (np.zeros
), then replace the rows with your a
and b
. Not sure that's any better than your way though
In [27]: a=range(40)
In [28]: b=range(30)
In [29]: x=np.zeros((2,max(len(a),len(b))))
In [30]: for i,j in enumerate([a,b]): x[i][:len(j)]=j
In [31]: x
Out[31]:
array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32.,
33., 34., 35., 36., 37., 38., 39.],
[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23., 24., 25., 26., 27., 28., 29., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0.]])
Upvotes: 1