使用numpy在数组中转置数据

时间:2013-06-25 16:13:42

标签: numpy

我有以下列表,需要转换为numpy数组

samplelist= [  [ ['Name-1','Name-2','Name-3']            , ['Age-1','Age-2','Age-3'] ],
               [ ['new_Name_1','new_Name_2','new_Name_3'], ['new_Age_1','new_Age_2','new_Age_3'] ]
             ]

预期结果:

samplearray = [ [ ['Name-1','Age-1'],         ['Name-2','Age-2'],        ['Name-3','Age-3'] ],
                [ ['new_Name_1','new_Age_1],  ['new_Name_2','new_Age_2'], ['new_Name_3','new_Age_3'] ]
               ]

np.transpose结果:

np.transpose(a)
array([[['Name-1', 'new_Name_1'],
        ['Age-1', 'new_Age_1']],

       [['Name-2', 'new_Name_2'],
        ['Age-2', 'new_Age_2']],

       [['Name-3', 'new_Name_3'],
        ['Age-3', 'new_Age_3']]], 
      dtype='|S10')

1 个答案:

答案 0 :(得分:4)

samplelist是一个三维数组。

In [58]: samplelist.shape
Out[58]: (2, 2, 3)

使用转置交换第一个和最后一个轴(0和2):

In [55]: samplelist.T
Out[55]: 
array([[['Name-1', 'new_Name_1'],
        ['Age-1', 'new_Age_1']],

       [['Name-2', 'new_Name_2'],
        ['Age-2', 'new_Age_2']],

       [['Name-3', 'new_Name_3'],
        ['Age-3', 'new_Age_3']]], 
      dtype='|S10')

In [57]: samplelist.swapaxes(0,2)
Out[57]: 
array([[['Name-1', 'new_Name_1'],
        ['Age-1', 'new_Age_1']],

       [['Name-2', 'new_Name_2'],
        ['Age-2', 'new_Age_2']],

       [['Name-3', 'new_Name_3'],
        ['Age-3', 'new_Age_3']]], 
      dtype='|S10')

要获得所需的数组,请交换轴1和2:

import numpy as np
samplelist = np.array([
    [ ['Name-1','Name-2','Name-3']            , ['Age-1','Age-2','Age-3'] ],
    [ ['new_Name_1','new_Name_2','new_Name_3'], ['new_Age_1','new_Age_2','new_Age_3'] ]
    ])

print(samplelist.swapaxes(1,2))
# [[['Name-1' 'Age-1']
#   ['Name-2' 'Age-2']
#   ['Name-3' 'Age-3']]

#  [['new_Name_1' 'new_Age_1']
#   ['new_Name_2' 'new_Age_2']
#   ['new_Name_3' 'new_Age_3']]]