tags:

views:

85

answers:

6

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)?

+5  A: 

Try column_stack()?

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

Alternatively,

vstack((a,b)).T
Amber
This creates a three-dimensional array.
Philipp
Already ahead of you, Philipp. :)
Amber
A: 

I forget how to transpose numpy arrays; but you could do:

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

result = vstack((a,b))
Nathan Fellman
Transposing one-dimensional arrays is an identity operation.
Philipp
Feel free to fix the syntax. Like I said, I forgot how to transpose a numpy array.
Nathan Fellman
A: 

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

anijhaw
+3  A: 

column_stack.

Philipp
A: 
>>> 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
This question is about NumPy arrays, not lists.
Amber
@Amber - `zip` still seems to work with arrays.
mtrw
Yes, but it will most likely be slower than the proper NumPy functions.
Amber
@Amber - True. I had never stumbled across `column_stack` before, your answer is definitely better.
mtrw
A: 
numpy.vstack((a, b)).T
Cheery