3

Let's say I have this matrix m of dimensions 9 x 9 x 26:

[[['a00', ... 'z00'], ['a01', ... 'z01'], ... ['a09', ... 'z09']],
[['a10', ... 'z10'], ['a11', ... 'z11'], ... ['a19', ... 'z19']],
...
[['a90', ... 'z90'], ['a91', ... 'z91'], ... ['a99', ... 'z99']]]

I want to convert A to the following matrix of dimensions 26 x 81:

 [['a00', 'a01', ... 'a09', 'a10', ... 'a19', ... 'a99'],
  ['z00', 'z01', ... 'z09', 'z10', ... 'z19', ... 'z99']]

What's the best way of doing this in python?

Leeren
  • 1,931
  • 2
  • 20
  • 31
  • It looks like what you are looking for is not the transpose. Transposing a matrix is like rotating it. You want to [reshape](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) it. You can find several examples here on SO like [this](http://stackoverflow.com/questions/14476415/reshape-an-array-in-numpy?rq=1). – iled Feb 08 '16 at 00:06
  • Is this actually a numpy array? – Padraic Cunningham Feb 08 '16 at 00:07
  • Sorry for not making this clear; yeah I wanted to ask specifically about lists! – Leeren Feb 08 '16 at 00:24

2 Answers2

4

If you have a list and not a numpy array:

m = [[['a00',  'z00'], ['a01',  'z01'],  ['a09',  'z09']],
[['a10',  'z10'], ['a11',  'z11'],  ['a19',  'z19']],   
[['a90',  'z90'], ['a91',  'z91'],  ['a99',  'z99']]]

from itertools import chain
print zip(*(chain(*m))

[('a00', 'a01', 'a09', 'a10', 'a11', 'a19', 'a90', 'a91', 'a99'), 
('z00', 'z01', 'z09', 'z10', 'z11', 'z19', 'z90', 'z91', 'z99')]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
3

Is this the kind of reordering you want?

In [128]: a=[[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]]]

In [129]: A=np.array(a)

In [130]: A
Out[130]: 
array([[[11, 12, 13],
        [14, 15, 16]],

       [[21, 22, 23],
        [24, 25, 26]]])

In [131]: A.reshape(-1,3).T
Out[131]: 
array([[11, 14, 21, 24],
       [12, 15, 22, 25],
       [13, 16, 23, 26]])

A is (2,2,3), and result is (3,4).

I reshaped it into (4,3), and then transposed the 2 axes.

Sometimes questions like this are confusing, especially if they don't have a concrete example to test. If I didn't get it right, I made need to apply the transpose first, with a full specification.

e.g.

In [136]: A.transpose([2,0,1]).reshape(3,-1)
Out[136]: 
array([[11, 14, 21, 24],
       [12, 15, 22, 25],
       [13, 16, 23, 26]])

If you have lists, as opposed an array, the task will be more difficult. There is an easy idiom for 'transposing' a '2d' nested list, but it might not apply to '3d'.

In [137]: zip(*a)
Out[137]: [([11, 12, 13], [21, 22, 23]), ([14, 15, 16], [24, 25, 26])]

(ok, the other answer has the non-array solution).

hpaulj
  • 221,503
  • 14
  • 230
  • 353