重塑嵌套数组

时间:2021-04-21 17:23:29

标签: python arrays numpy

我目前有一个形状为 (27,) 的 ndarray,其中每个数组条目都是一个形状为 (121,61) 的数组。我想将 ndarray 重塑为 (3267, 61) 的新大小,这只是将嵌套数组扩展/展平为一个。

我曾尝试使用 .resize(3267, 61) 和 .reshape(3267, 61) 但当我这样做时,出现以下错误:

ValueError: 无法将大小为 27 的数组重塑为形状 (3267, 61)

ValueError: 无法调整这个数组的大小:它不拥有它的数据

2 个答案:

答案 0 :(得分:3)

您可以使用 np.stack() 将一系列数组转换为单个 ndarray,然后可以根据需要对其进行整形:

>>> a = np.zeros((27,), dtype=object)
>>> for i in range(a.shape[0]):
    ... a[i] = np.zeros((121, 61))
>>> b = np.stack(a).reshape((27*121, 61))
>>> b.shape
    (3267, 61)

答案 1 :(得分:2)

如果数组元素确实是其他一维 nDarray(正如@CamiloMartínez 表明它可能发生的那样),则使用:

b = np.concatenate(a)

如果数组只是一个 3D 数组(例如,通过将数组列表放在一起并让 numpy 对其进行优化而获得),则使用:

b = a.reshape(-1, a.shape[-1])

一般情况:如果您不确定,那么以下两种情况都适用。它也适用于 a 是包含数组的二维(或更高维度)数组的情况(正如@drod31 在评论中所问的那样):

b = np.stack(a.ravel())
b = b.reshape(-1, b.shape[-1])

这是一个最小的例子:

案例 1:(感谢 @CamiloMartínez 的设置)。

a = np.empty((27,), dtype=object)
for i in range(a.shape[0]):
    a[i] = np.zeros((121, 61))

b = np.concatenate(a)
>>> b.shape
(3267, 61)

case 2(我的初始设置,错过了实际的数组条件数组):

a = np.array([np.zeros((121, 61)) for _ in range(27)])

b = a.reshape(-1, a.shape[-1])

>>> b.shape
(3267, 61)

无论如何,您通常希望在没有明确硬编码维度的情况下表达转换,以便更广泛地使用。

角落案例(根据@drod31 问题):

a = np.empty((15,27), dtype=object)
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        a[i,j] = np.zeros((121, 61))

>>> a.shape
(15, 27)

>>> a[0,0].shape
(121, 61)

b = np.stack(a.ravel())
b = b.reshape(-1, b.shape[-1])

>>> b.shape
(49005, 61)