[英]Create an ndarray from arrays of different lengths
How do you elegantly create a NumPy ndarray
from (1D-)arrays of different lengths, padding the remainder? 如何从不同长度的(1D-)数组优雅地创建NumPy ndarray
,并填充其余部分?
The arrays are always 1D, they have different lengths (maximum length varied between 20 and 100). 数组始终是一维的,它们具有不同的长度(最大长度在20到100之间变化)。
Say there is 说有
a = range(40)
b = range(30)
The resultant ndarray
should be 结果ndarray
应该是
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 并通过填充maximum
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? 可以工作,但是没有内置的东西/通过PyPI可用/更多pythonic吗?
You could create an array of zeros ( np.zeros
), then replace the rows with your a
and b
. 您可以创建一个零数组( np.zeros
),然后用a
和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.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.