将数组重塑为方形数组Python

时间:2015-11-10 15:23:24

标签: python arrays numpy concatenation reshape

我有一组数字,其形状为26*43264。我想将其重塑为一个形状208*208的数组,但是只有26*26的块。

[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10,11,12,13,14,15,16,17,18,19]]

变得像:

[[0, 1, 2, 3, 4],
[10,11,12,13,14],
[ 5, 6, 7, 8, 9],
[15,16,17,18,19]]

2 个答案:

答案 0 :(得分:3)

之前出现过这种重塑问题。但不是搜索我会迅速展示出一种笨拙的方法

制作样本数组:

In [473]: x=np.arange(20).reshape(2,10)
In [474]: x
Out[474]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

使用重塑将其拆分为5个块

In [475]: x.reshape(2,2,5)
Out[475]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]]])

并使用转置重新排序维度,并实际重新排序这些行

In [476]: x.reshape(2,2,5).transpose(1,0,2)
Out[476]: 
array([[[ 0,  1,  2,  3,  4],
        [10, 11, 12, 13, 14]],

       [[ 5,  6,  7,  8,  9],
        [15, 16, 17, 18, 19]]])

和其他形状来巩固前2个维度

In [477]: x.reshape(2,2,5).transpose(1,0,2).reshape(4,5)
Out[477]: 
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [ 5,  6,  7,  8,  9],
       [15, 16, 17, 18, 19]])

如果x已经是一个numpy数组,那么这些转置和重塑操作都很便宜(时间紧迫)。如果x是真正嵌套的列表,那么带有列表操作的其他解决方案会更快,因为使numpy数组有开销。

答案 1 :(得分:1)

有点难看,但这里有一个小内容,你应该可以修改一个完整尺寸的小例子:

In [29]: from itertools import chain

In [30]: np.array(list(chain(*[np.arange(20).reshape(4,5)[i::2] for i in xrange(2)])))
Out[30]:
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [ 5,  6,  7,  8,  9],
       [15, 16, 17, 18, 19]])

编辑:这是函数中更通用的版本。 Uglier代码,但该函数只需要一个数组和一些你想最终得到的段。

In [57]: def break_arr(arr, chunks):
   ....:     to_take = arr.shape[1]/chunks
   ....:     return np.array(list(chain(*[arr.take(xrange(x*to_take, x*to_take+to_take), axis=1) for x in xrange(chunks)])))
   ....:

In [58]: arr = np.arange(40).reshape(4,10)

In [59]: break_arr(arr, 5)
Out[59]:
array([[ 0,  1],
       [10, 11],
       [20, 21],
       [30, 31],
       [ 2,  3],
       [12, 13],
       [22, 23],
       [32, 33],
       [ 4,  5],
       [14, 15],
       [24, 25],
       [34, 35],
       [ 6,  7],
       [16, 17],
       [26, 27],
       [36, 37],
       [ 8,  9],
       [18, 19],
       [28, 29],
       [38, 39]])

In [60]: break_arr(arr, 2)
Out[60]:
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [20, 21, 22, 23, 24],
       [30, 31, 32, 33, 34],
       [ 5,  6,  7,  8,  9],
       [15, 16, 17, 18, 19],
       [25, 26, 27, 28, 29],
       [35, 36, 37, 38, 39]])