如何重整形元组数组

时间:2018-09-03 15:36:16

标签: python numpy reshape

我需要重塑numpy数组以绘制一些数据。 以下工作正常:

import numpy as np
target_shape = (350, 277)
arbitrary_array = np.random.normal(size = 96950)
reshaped_array = np.reshape(arbitrary_array, target_shape)

但是,如果不是数组的形状(96950,),我有一个元组数组,每个元组都有3个元素(96950,3),我得到了一个

cannot reshape array of size 290850 into shape (350,277)

这里是复制错误的代码

array_of_tuple = np.array([(el, el, el) for el in arbitrary_array])
reshaped_array = np.reshape(array_of_tuple, target_shape)

我猜想,重塑的作用是将元组数组展平(因此大小为290850),然后尝试重塑它。但是,我想拥有的是形状为(350,277)的元组数组,基本上忽略了第二维,只是在标量为元组时对其进行了重塑。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以改成(350, 277, 3)

>>> a = np.array([(x,x,x) for x in range(10)])
>>> a.reshape((2,5,3))
array([[[0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4]],

       [[5, 5, 5],
        [6, 6, 6],
        [7, 7, 7],
        [8, 8, 8],
        [9, 9, 9]]])

从技术上讲,结果不会是3个元组的350x277 2D数组,而是350x277x3 3D数组,但是您的array_of_tuple既不是实际的“元组数组”,而是2D数组

答案 1 :(得分:1)

reshaped_array=np.reshape(array_of_tuple,(350,-1))
reshaped_array.shape

给予(350,831)

由于覆盖数组的整个元素的列号和行号不匹配,您会收到错误消息

350*831= 290850   where as
350*277=96950 

,因此numpy不知道如何处理数组的其他元素,您可以尝试减小数组的原始大小以减少元素的数量。如果您不想删除元素,则

reshape(350,277,3)

是一个选择

答案 2 :(得分:1)

您对问题np.array(iterable)的误解导致了问题,请看一下

In [7]: import numpy as np

In [8]: np.array([(el, el, el) for el in (1,)])
Out[8]: array([[1, 1, 1]])

In [9]: _.shape
Out[9]: (1, 3)

问自己是

的形状
array_of_tuple = np.array([(el, el, el) for el in np.random.normal(size = 96950)])
相关问题