Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the numpy equivalent of python's zip(*)?

Tags:

python

zip

numpy

I think (hope) this question differs substantially from What is the equivalent of "zip()" in Python's numpy?, although it might just be my ignorance.

Let's say I have the following:

[[[ 1,  2],
  [ 3,  4],
  [ 5,  6]],
 [[ 7,  8],
  [ 9, 10],
  [11, 12]]]

and I want to turn it into

[[[ 1,  2],
  [ 7,  8]],
 [[ 3,  4],
  [ 9, 10]],
 [[ 5,  6],
  [11, 12]]]

In python I can do:

>>> foo
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
>>> zip(*foo)
[([1, 2], [7, 8]), ([3, 4], [9, 10]), ([5, 6], [11, 12])]

But how can I do this with numpy arrays (without using zip(*))?

like image 403
rhombidodecahedron Avatar asked Jul 19 '13 19:07

rhombidodecahedron


1 Answers

Do you actually need to return tuples or do you want to reshape the array?

>>> a
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6]],

       [[ 7,  8],
        [ 9, 10],
        [11, 12]]])

>>> a.swapaxes(0,1)
array([[[ 1,  2],
        [ 7,  8]],

       [[ 3,  4],
        [ 9, 10]],

       [[ 5,  6],
        [11, 12]]])
like image 89
Daniel Avatar answered Oct 08 '22 11:10

Daniel