如何重塑元组数组

问题描述 投票:1回答:3

我需要重塑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),基本上忽略了第二维,只是重塑了元组,因为它们是标量。有没有办法实现这个目标?

python numpy reshape
3个回答
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]]])

从技术上讲,结果不会是350x277二维阵列的3元组,而是一个350x277x3的3D阵列,但是你的array_of_tuple既不是实际的“元组阵列”,也不是2D阵列。


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)

是一个选择


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)])
© www.soinside.com 2019 - 2024. All rights reserved.