如何以这种方式重塑numpy数组?

时间:2018-03-23 16:07:59

标签: arrays python-3.x numpy multidimensional-array reshape

我想将a重塑为b,如何快速完成?

基本上,在重塑阵列时,如何始终使用每组中的第一项,然后是第二项,那么第三项呢?

输入:

import numpy as np

# 3 repeats, each has 2 variables, each has 4 times
a=np.array([[['r1_v1_t1','r1_v1_t2','r1_v1_t3','r1_v1_t4'],
            ['r1_v2_t1','r1_v2_t2','r1_v2_t3','r1_v2_t4']],

[['r2_v1_t1','r2_v1_t2','r2_v1_t3','r2_v1_t4'],
            ['r2_v2_t1','r2_v2_t2','r2_v2_t3','r2_v2_t4']],

[['r3_v1_t1','r3_v1_t2','r3_v1_t3','r3_v1_t4'],
            ['r3_v2_t1','r3_v2_t2','r3_v2_t3','r3_v2_t4']]
            ])

# 4 times, each has 3 repeats, each has 2 variables
b=np.array([[['r1_v1_t1','r1_v2_t1'],['r2_v1_t1','r2_v2_t1'],['r3_v1_t1','r3_v2_t1']],
[['r1_v1_t2','r1_v2_t2'],['r2_v1_t2','r2_v2_t2'],['r3_v1_t2','r3_v2_t2']],
[['r1_v1_t3','r1_v2_t3'],['r2_v1_t3','r2_v2_t3'],['r3_v1_t3','r3_v2_t3']],
[['r1_v1_t4','r1_v2_t4'],['r2_v1_t4','r2_v2_t4'],['r3_v1_t4','r3_v2_t4']]])

# 4 times, each has 2 variables, each has 3 repeats
#print(a.T)

#print(np.reshape(a,(4,3,2), order='F')) not work
#print(np.reshape(a,(4,3,2))) not work

1 个答案:

答案 0 :(得分:1)

您可以交换数组的轴,使a的形状与b的形状相匹配。 Numpy的swapaxes可以做到这一点:

new_a = np.swapaxes( np.swapaxes(a,0,2) ,1,2)

您可以测试此new_a是否等同于b

print (new_a == b).all()  # True

这是一个有效的gist