重塑数组的数组错误:*** IndexError:元组索引超出范围

时间:2018-08-30 21:53:39

标签: arrays python-2.7 numpy reshape flatten

l有一个称为my_data的数组,这样: 类型为<type 'numpy.ndarray'> dimension(my_data)= [96,18,36,36,3]

但是,my_data.shape返回(96,),但我希望得到(96,18,36,36,3)。之后,我尝试my_data[0].shape返回(18,)而不是(18,36,36,3),最后my_data[0][0].shape返回(36,36,3)。

我想知道为什么我没有得到(96,18,36,36,3)的形状

为什么需要它?

l想将my_data重塑为(96,18,36*36*3)

谁曾尝试过?

my_data=my_data.reshape(my_data.shape[0],my_data.shape[1],my_data.shape[2]*my_data.shape[3]*my_data.shape[4])

l出现以下错误:

 *** IndexError: tuple index out of range

1 个答案:

答案 0 :(得分:0)

我什至不确定您是如何到达其中包含np.array的{​​{1}}的。但是,如果数据对齐,则简单的转换应该可以为您解决问题,例如:

np.array

如果数据未对齐,则应首先将其对齐:

import numpy as np

x = [np.random.randint(1, 100, (2, 3, 4)) for _ in range(2 * 3)]
x = np.array(x)
x.shape
# (6, 2, 3, 4)

注意:此import numpy as np x = [np.random.randint(1, 100, (2, 3, np.random.randint(1, 5))) for _ in range(2 * 3)] print([y.shape for y in x]) # [(2, 3, 2), (2, 3, 1), (2, 3, 1), (2, 3, 4), (2, 3, 1), (2, 3, 1)] # x = np.array(x) will cause ValueError... def zero_padding(arr, shape): result = np.zeros(shape, dtype=arr.dtype) mask = tuple(slice(None, d) for d in arr.shape) result[mask] = arr return result x = [zero_padding(y, (2, 3, 4)) for y in x] x = np.array(x) x.shape # (6, 2, 3, 4) 的更复杂的版本由NumPy的zero_padding()FlyingCircuspad()提供。

免责声明:我是FlyingCircus的主要作者。