列出 Numpy 数组并重塑(维度问题)

时间:2021-02-11 20:37:44

标签: python list numpy reshape

我有一个附加 2 个 numpy 数组的列表。

mylist=

[array([[5.45, 2.97, 6.25],
        [7.27, 5.28, 4.18]]),
array([[4.54, 2.06, 2.53],
       [7.2, 5.28, 1.29]])]

我想从此列表中重新创建 numpy 数组,如下所示:

array([[5.45, 2.97, 6.25,4.54, 2.06, 2.53]],
       [7.27, 5.28, 4.18,7.2, 5.28, 1.29]])

我尝试了 np.array(mylist).reshape(2,6),但结果不是我的目标。

2 个答案:

答案 0 :(得分:1)

arr = np.array(mylist)
arr

>>> [[[5.45, 2.97, 6.25],
      [7.27, 5.28, 4.18]],

     [[4.54, 2.06, 2.53],
      [7.2 , 5.28, 1.29]]]

你需要在重塑前交换第一和第二个轴

brr = arr.transpose([1, 0, 2]).reshape(2, -1)
brr

>>> [[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
     [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]]

答案 1 :(得分:1)

In [145]: alist = [np.array([[5.45, 2.97, 6.25],
     ...:         [7.27, 5.28, 4.18]]),
     ...:         np.array([[4.54, 2.06, 2.53],
     ...:         [7.2, 5.28, 1.29]])]

In [147]: np.hstack(alist)
Out[147]: 
array([[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
       [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]])

这只是一种紧凑的调用方式

In [148]: np.concatenate(alist, axis=1)
Out[148]: 
array([[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
       [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]])