将 numpy 数组重塑为所需的形状

Reshaping a numpy array into desired shape

我在 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]]

我只想使用重塑和转置函数并获得以下数组:

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

这能做到吗?我已经花了几个小时尝试,但我开始认为这是不可能完成的 - 我是否遗漏了一些明显的东西?

您可以重塑成列,然后转置,然后用类似的东西重塑:

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]])

您可以尝试将 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]])