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 次元配列です。

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 に答える