从不同长度的数组创建ndarray [英] Create an ndarray from arrays of different lengths
本文介绍了从不同长度的数组创建ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用不同长度的(1D-)数组优雅地创建NumPy ndarray
,并填充其余部分?
How do you elegantly create a NumPy ndarray
from (1D-)arrays of different lengths, padding the remainder?
数组始终是一维的,它们具有不同的长度(最大长度在20到100之间变化).
The arrays are always 1D, they have different lengths (maximum length varied between 20 and 100).
说有
a = range(40)
b = range(30)
结果ndarray
应该是
X = [[0,1,2,3,...,39,40],
[0,1,2,...29,30,0,0,...,0]]
棘手的解决方案
创建中介
Hacky solution
Creating an intermediary
I = [a,b]
并通过
I[1].extend([0] * (maximum - len(I[1])))
然后可以通过
X = np.array(I)
可以工作,但是没有内置的东西/可以通过PyPI使用/更多的pythonic吗?
works but is there nothing built-in / available via PyPI / more pythonic?
推荐答案
您可以创建零数组(np.zeros
),然后用a
和b
替换行.不确定是否比您的方式更好
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.]])
这篇关于从不同长度的数组创建ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文