2

我有以下列表,需要转置为 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')
4

1 回答 1

4

samplelist是一个 3-D 数组。

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']]]
于 2013-06-25T16:21:33.533 回答