簡體   English   中英

如何重塑元組數組

[英]how to reshape an array of tuples

我需要重塑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),基本上忽略了第二個維度,只是重塑了元組,因為它們是標量。 有沒有辦法實現這個目標?

您可以重塑為(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陣列。

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)

是一個選擇

你的問題從對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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM