Numpy 将大小未知的二维阵列组合成一个三维阵列
我有一个函数,比如peaksdetect(),它将生成一个未知行数的二维数组;我会叫它几次,比如说3,我想用这3个数组,一个3-D数组。这是我的开始,但它非常复杂,有很多if语句,因此我希望尽可能简化:Numpy 将大小未知的二维阵列组合成一个三维阵列,numpy,Numpy,我有一个函数,比如peaksdetect(),它将生成一个未知行数的二维数组;我会叫它几次,比如说3,我想用这3个数组,一个3-D数组。这是我的开始,但它非常复杂,有很多if语句,因此我希望尽可能简化: import numpy as np dim3 = 3 # the number of times peaksdetect() will be called # it is named dim3 because this number will determine
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
...
如果您希望调整数组的大小,那么预分配它很可能不会带来太多好处。将数组存储在列表中可能会更简单,然后计算数组的大小以容纳所有数组,并将数据转储到其中:
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
真是太棒了!事实上,我对Python的基础知识一无所知,例如什么是列表。