将numpy数组重塑为所需形状

时间:2020-03-10 22:54:09

标签: python numpy matrix reshape numpy-ndarray

我正在用numpy工作,并具有以下形式的numpy数组;

[[ 1,  2,  3],
 [ 4,  5,  6],
 [ 7,  8,  9],
 [10, 11, 12],
 [13, 14, 15],
 [16, 17, 18],
 [19, 20, 21],
 [22, 23, 24]]

我只想使用reshape和transpose函数并获得以下数组:

[[ 1,  2,  3,  7,  8,  9, 13, 14, 15, 19, 20, 21],
 [ 4,  5,  6, 10, 11, 12, 16, 17, 18, 22, 23, 24]]

可以做到吗?我已经花了几个小时尝试,并且开始认为它无法完成-我是否缺少明显的东西?

2 个答案:

答案 0 :(得分:4)

您可以将其重塑为列,然后转置,然后使用类似的方法重塑:

a = np.array([[ 1,2,3],
 [ 4,5,6],
 [ 7,8,9],
 [10, 11, 12],
 [13, 14, 15],
 [16, 17, 18],
 [19, 20, 21],
 [22, 23, 24]])

a.reshape(-1, 2, 3).transpose((1, 0, 2)).reshape(2, -1)

# array([[ 1,  2,  3,  7,  8,  9, 13, 14, 15, 19, 20, 21],
#        [ 4,  5,  6, 10, 11, 12, 16, 17, 18, 22, 23, 24]])

答案 1 :(得分:0)

您可以尝试切片oddeven并将它们传递给np.reshape

a_out = np.reshape([a[::2], a[1::2]], (2,-1))

Out[81]:
array([[ 1,  2,  3,  7,  8,  9, 13, 14, 15, 19, 20, 21],
       [ 4,  5,  6, 10, 11, 12, 16, 17, 18, 22, 23, 24]])