2012-03-19 185 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