2012-03-19 148 views
3

我很难在飞行中创建numpy 2D阵列。动态创建动态2D numpy阵列

所以基本上我有一个for循环这样的事情。

for ele in huge_list_of_lists: 
    instance = np.array(ele) # creates a 1D numpy array of this list 
# and now I want to append it to a numpy array 
# so basically converting list of lists to array of arrays? 
# i have checked the manual.. and np.append() methods 
that doesnt work as for np.append() it needs two arguments to append it together 

任何线索?

回答

5

创建2D阵列前面,并填补行而循环:

my_array = numpy.empty((len(huge_list_of_lists), row_length)) 
for i, x in enumerate(huge_list_of_lists): 
    my_array[i] = create_row(x) 

其中create_row()返回一个列表或长度0​​的1D阵列NumPy的。

根据create_row()的作用,可能会有更好的方法避免Python循环。

4

只要将列表的列表传递给numpy.array,请记住numpy数组是ndarrays,所以列表列表的概念不会转换为它转换为2d数组的数组数组。

>>> import numpy as np 
>>> a = [[1., 2., 3.], [4., 5., 6.]] 
>>> b = np.array(a) 
>>> b 
array([[ 1., 2., 3.], 
     [ 4., 5., 6.]]) 
>>> b.shape 
(2, 3) 

而且ndarrays已经ND-索引所以[1][1]成为[1, 1]在numpy的:

>>> a[1][1] 
5.0 
>>> b[1, 1] 
5.0 

我误解你的问题?

你挑衅地不想使用numpy.append这样的东西。请记住,numpy.append具有O(n)的运行时间,所以如果你调用它n次,对于你阵列的每一行调用一次,你最终会得到一个O(n^2)算法。如果您需要在知道所有内容的内容之前创建数组,但您知道最终大小,最好使用numpy.zeros(shape, dtype)创建一个数组,并在稍后填写。类似于斯文的回答。

2

import numpy as np

ss = np.ndarray(shape=(3,3), dtype=int);

array([[    0, 139911262763080, 139911320845424], 
    [  10771584,  10771584, 139911271110728], 
    [139911320994680, 139911206874808,    80]]) #random 

numpy.ndarray功能实现这一点。 numpy.ndarray