1

I am having a problem splicing together two arrays. Let's assume I have two arrays:

a = array([1,2,3])
b = array([4,5,6])

When I do vstack((a,b)) I get

[[1,2,3],[4,5,6]]

and if I do hstack((a,b)) I get:

[1,2,3,4,5,6]

But what I really want is:

[[1,4],[2,5],[3,6]]

How do I accomplish this without using for loops (it needs to be fast)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siggi
  • 319
  • 3
  • 11
  • possible duplicate of [How do I iterate over the tuples of the items of two or more lists in Python?](http://stackoverflow.com/questions/1210396/how-do-i-iterate-over-the-tuples-of-the-items-of-two-or-more-lists-in-python) [how can I iterate through two lists in parallel in Python?](http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python-closed) – Nathan Fellman Jul 21 '10 at 18:24
  • No duplicate; the other threads aren't related to numpy. – Philipp Jul 21 '10 at 18:30
  • 1
    I'm curious why you accepted Philipp's answer, when it was identical to, and submitted later than, Amber's answer? – mtrw Jul 21 '10 at 18:53
  • 1
    @mtrw Because Amber modified his/her answer. He/she suggested vstack first – NullUserException Jul 21 '10 at 19:17
  • @NullUser - Looking at the edit history, the edit only added the `vstack().T` option. – mtrw Jul 21 '10 at 19:26
  • @mtrw That's because the answer was edited within the 5 minute "grace period." I saw the original. – NullUserException Jul 21 '10 at 20:02
  • @NullUser - That would definitely explain it. Thanks, and I withdraw my question. – mtrw Jul 21 '10 at 20:14
  • I actually suggested `dstack` first, not vstack; but then remembered that dstack adds in the 3rd dimension (even if stripping off one dimension then does give the correct answer). – Amber Jul 21 '10 at 20:44

6 Answers6

7

Try column_stack()?

http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html

Alternatively,

vstack((a,b)).T
Amber
  • 507,862
  • 82
  • 626
  • 550
4

column_stack.

Philipp
  • 48,066
  • 12
  • 84
  • 109
0

I forgot how to transpose NumPy arrays, but you could do:

at = transpose(a)
bt = transpose(b)

result = vstack((a,b))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
0
>>> c = [list(x) for x in zip(a,b)]
>>> c
[[1, 4], [2, 5], [3, 6]]

or

>>> c = np.array([list(x) for x in zip(a,b)])
>>> c
array([[1, 4],
       [2, 5],
       [3, 6]])

depending on what you're looking for.

mtrw
  • 34,200
  • 7
  • 63
  • 71
0
numpy.vstack((a, b)).T
Cheery
  • 24,645
  • 16
  • 59
  • 83
-1

You are probably looking for shape manipulation of the array. You can look in the "Tentative NumPy Tutorial, Array Creation".

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
anijhaw
  • 8,954
  • 7
  • 35
  • 36