2013-04-20 66 views
2

我有一個函數,比如說說peaksdetect(),它會生成未知行數的二維數組;我會稱它爲幾次,讓我們說3,我想用這3個數組,一個3-D數組。這裏是我的開始,但它是非常複雜,有很多的if語句,所以我想打,如果可能的事情變得更簡單:將未知大小的二維數組組合成一個3-D

import numpy as np 

dim3 = 3 # the number of times peaksdetect() will be called 
      # it is named dim3 because this number will determine 
      # the size of the third dimension of the result 3-D array 

for num in range(dim3): 
    data = peaksdetect(dataset[num])   # generates a 2-D array of unknown number of rows 
    if num == 0: 
     3Darray = np.zeros([dim3, data.shape]) # in fact the new dimension is in position 0 
               # so dimensions 0 and 1 of "data" will be 
               # 1 and 2 respectively 
    else: 
     if data.shape[0] > 3Darray.shape[1]: 
      "adjust 3Darray.shape[1] so that it equals data[0] by filling with zeroes" 
      3Darray[num] = data 
     else: 
      "adjust data[0] so that it equals 3Darray.shape[1] by filling with zeroes" 
      3Darray[num] = data 
... 

回答

2

如果您在具有調整您的陣列計算,這就有可能不會通過預分配來獲得很多。這將可能是簡單的數組存儲在一個列表中,然後計算出數組的大小來加以描述,數據轉儲到它:

data = [] 
for num in range(dim3): 
    data.append(peaksdetect(dataset[num])) 
shape = map(max, zip(*(j.shape for j in data))) 
shape = (dim3,) + tuple(shape) 
data_array = np.zeros(shape, dtype=data[0].dtype) 
for j, d in enumerate(data): 
    data_array[j, :d.shape[0], :d.shape[1]] = d 
+0

作品好了!事實上,我對Python中的基礎知識一無所知,例如什麼是列表。 – user1850133 2013-04-21 11:59:27

相關問題