numpy - 将未知大小的 2-D 数组组合起来形成一个 3-D

标签 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 
           # 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

关于numpy - 将未知大小的 2-D 数组组合起来形成一个 3-D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16124695/

相关文章:

python - 在numpy的混淆矩阵中获取与每种错误类型实例对应的索引

python - 理解 Michael Nielsen 的反向传播代码

python - 从 3D Numpy 数组绘制红色 channel

python - 如何计算 PIL 逊相关矩阵并仅保留有效值?

python - 查找二维点组之间的最小距离(快速且不太消耗内存)

python - `numpy.positive`的用例

python - numpy 和 theano 中的 3D 矩阵乘法

python - 确定 ‘data’ 的平均值,其中 CONTINUOUS cond=True 的最高数量

python - 排列数组 : Exclude NaN and assign lowest rank to highest number

python - numpy:使用 column_stack 时是否可以保留列的 dtype