2

I have list as following and need to be tranposed to a numpy array

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

Expected Result:

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 results:

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')
3
  • well, what did you tried? Have you googled for "numpy transpose"? Commented Jun 25, 2013 at 16:15
  • Yes, I did and I have given the results... Commented Jun 25, 2013 at 16:20
  • numpy.transpose gives different than your result. So, it is not directly the transpose I guess. Commented Jun 25, 2013 at 16:21

1 Answer 1

4

samplelist is a 3-D array.

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

Using transpose swaps the first and last axes (0 and 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')

To get the desired array, swap axes 1 and 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']]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.