numpy 在指定维度上以任意维度大小堆叠数组

iyr7buue  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(114)

考虑以下数据:

data = np.array([[i for i in range(3)] for _ in range(9)])
print(data)
print(f'data has shape {data.shape}')

[[0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]]
data has shape (9, 3)

还有一个参数,我们称之为history。history的功能是,它在第一维上堆叠history许多数组[0 1 2]。作为一个示例,考虑使用history=2对该过程进行一次迭代

history = 2
data = np.array([[[0, 1, 2], [0, 1, 2]]])
print(f'data has now shape {data.shape}')
data has now shape (1, 2, 3)

现在,让我们考虑两个迭代:

history = 2
data = np.array([[[0, 1, 2], [0, 1, 2]],[[0, 1, 2], [0, 1, 2]]])
print(f'data has now shape {data.shape}')
data has now shape (2, 2, 3)

应重复此过程,直到数据完全处理。这意味着,我们可能会在最后丢失一些数据,因为data.shape[0]/history % 2 != 0。因此,history=2的最终结果为

([[[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]]])

如何才能做到这一点的性能?

xoshrz7s

xoshrz7s1#

如果我没理解错的话,你可以先切片,然后再整形:

history = 2

out = data[:data.shape[0]//history*history].reshape((-1, history, data.shape[1]))

输出:

array([[[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]]])

相关问题